Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

FILES :

In C programming, file is a place on disk where a group of related data is stored.A set of records on the
disk is called as a file. Data is kept as a stream of characters in a file.

Various file status functions (or) various file system functions in C

C provides a number of functions that helps to perform basic file operations. Following are the
functions,

Function Description
1. fopen() create a new file or open a existing file
2. fclose() closes a file
3. getc() reads a character from a file
4. putc() writes a character to a file
5. fscanf() reads a set of data from a file
6. fprintf() writes a set of data to a file
7. getw() reads a integer from a file
8. putw() writes a integer to a file
9. fseek() set the position to desire point
10. ftell() gives current position in the file
11. rewind() set the position to the begining point

Working with file

While working with file, we need to declare a pointer of type file.

FILE *ptr;

File Operations

1. Creating a new file


2. Opening an existing file
3. Reading from and writing information to a file
4. Closing a file

Opening a file

Opening a file is performed using library function fopen(). The syntax for opening a file in standard I/O is:

ptr = fopen("FileName", "mode");


Example: fptr = fopen("one.txt", "w");
NOTE : If the file we want to open is not opened then NULL is returnrd by fopen( ) function.
File opening modes :
The mode of opening a file tells for what purpose (eg. reading, writing, appending etc.) the file is opened.

File opening modes :


Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing, if it does not exist then a new file is created. Here your program will start
writing content from the beginning of the file.
a Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here your
program will start appending content in the existing file content.
r+ Opens a text file for reading and writing both.
w+ Opens a text file for reading and writing both. It first truncate the file to zero length if it exists
otherwise create the file if it does not exist.
a+ Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will
start from the beginning but writing can only be appended.

Closing a File

The file should be closed after reading/writing of a file. Closing a file is performed using library function
fclose( ).

Syntax : fclose(fptr); // fptr is the file pointer.

NOTE : When a file is closed automatically, the EOF character is added as the last character of the file. Thus
for any text file , the last character is EOF character. EOF character can be supplied (entered) from the keyboard
by pressing ‘Ctrl’ and ‘z’ keys simultaneously.

Writing and Reading characters to a file :

Writing characters to a file :


- To write individual characters to a fle, first the file must be opened in write (“w”) mode.
Syntax : putc( char ch, FILE *fptr );
Eg. char ch;
FILE *fptr;
putc(ch, fptr);

Reading characters from a file :


- To read individual characters from a file, first the file must be opened in read (“r”)
mode.
Syntax : getc( FILE *fptr );
Eg. FILE *fptr;
getc(fptr);

- Write a program to create and write data in a file and read the data from that file. (or) Write a program in C
to create a file and write some text data in that file and read the data from that file and display the contents of
the file on the user screen.

#include <stdio.h>
main( )
{
char ch;
FILE *fptr;
clrscr();
printf("\n Enter contents for the file\n");
fptr = fopen("data.txt", "w"); /* Opening the file in write mode */
while( (ch=getchar( )) != '$') /* getchar( ) is for reading one character from the keyboard */
{
putc(ch, fptr); /* Writing one character in the file using putc( ) */
}
fclose(fptr);
fptr=fopen("data.txt", "r"); /* Opening the file for reading */
while( (ch=getc(fptr)) != EOF) /* Reading one character from the file using getc( ) */
{
printf("%c", ch); /* character taken from the file is assigned to ‘ch’ and printed on user screen */
}
fclose(fptr);
getch();
}
INPUT/OUTPUT : Enter contents for the file
Welcome to files concept.$
Welcome to files concept.

NOTE : putc( ) or fputc( ) can be used for writing characters. getc( ) or fgetc( ) can be used for reading
characters.
We can give any name as file name. .txt means it is a text file.

-Write a program in C that converts the contents of a file into capital letters and copy the contents in another
file. (This is also a C program to copy the contents of one file to another).
#include<stdio.h>
#include<ctype.h>
main( )
{
char ch;
FILE *p1, *p2;
clrscr();
printf("\n Enter data for the file \n\n");
p1=fopen("afile.txt", "w");
while( (ch=getchar( )) != '$')
{
putc(ch, p1);
}
fclose(p1);
p1=fopen("afile.txt", "r");
p2=fopen("bfile.txt", "w");
while( (ch=getc(p1)) != EOF )
{
putc(toupper(ch), p2); /* toupper( ) converts a small case alphabet to upper case */
} /* After conversion, the uppercase alphabet is written(copied) in ‘bfile’ */
fclose(p1);
fclose(p2);
printf("\n Contents of upper case file \n");
p2=fopen("bfile.txt", "r");
while( (ch=getc(p2)) != EOF)
printf("%c", ch);
fclose(p2);
getch();
}
INPUT/OUTPUT : Enter data for the file
Good Morning. Ready 123 start$
Contents of upper case file
GOOD MORNING. READY 123 START
NOTE : In the above program we are copying the contents of ‘afile’ to ‘bfile’. Before copying we are converting all the
lower case alphabets into upper case.
NOTE : toupper( ) function is in ctype.h header file. It converts only lower case alphabets into uppercase. It
does nothing for other characters. Similarly tolower( ) function converts upper case alphabets to
lower case.

-Write a program to split a Main_file into two files, say file1 and file2. Read lines into the Main_file from standard
input. File1 should consist of odd numbered lines and file2 should consist of even numbered lines.

#include<stdio.h>
main()
{
int num=1;
char ch;
FILE *p,*p1,*p2;
clrscr();
printf("\n Enter few lines of data for main file \n\n");
p=fopen("mainfile.txt", "w");
while( (ch=getchar( )) != ‘$’ ) /* At the end input ‘$’ symbol (here we can use any symbol to stop) */
{
putc(ch, p);
}
fclose(p);
p=fopen("mainfile.txt", "r");
p1=fopen("file1.txt", "w");
p2=fopen("file2.txt", "w");
while( (ch=getc(p)) != EOF )
{
if(ch=='\n')
num++;
if(num%2!=0)
putc(ch, p1); /* Copy the odd numbered lines in the file-1 */
else
putc(ch, p2); /* Copy the even numbered lines in file-2 */
}
fclose(p);
fclose(p1);
fclose(p2);
printf("\n Contents of File-1 \n");
p1=fopen("file1.txt", "r");
while( (ch=getc(p1)) != EOF )
printf("%c", ch);
fclose(p1);
printf("\n Contents of File-2 \n");
p2=fopen("file2.txt", "r");
while( (ch=getc(p2)) != EOF )
printf("%c", ch);
fclose(p2);
getch();
}

INPUT/OUTPUT : Enter few lines of data for main file


Hello good morning.
Files in C is easy.
No logic or magic.
Understand and remember syntax.
Contents of File-1
Hello good morning.
No logic or magic.
Contents of File-2
Files in C is easy.
Understand and remember syntax.

- Write a program to merge(append) two files. Append first file contents to the second file.

#include<stdio.h>
main( )
{
char ch;
FILE *p1,*p2;
clrscr( );
printf("\n Enter the data for first file \n\n");
p1=fopen("one.txt", "w");
while( (ch=getchar( )) != '$')
putc(ch, p1);
fclose(p1);
printf("\n Enter data for second file \n");
p2=fopen("two.txt", "w");
while( (ch=getchar( )) != '$')
putc(ch, p2);
fclose(p2);
p1=fopen("one.txt", "r");
p2=fopen("two.txt", "a");
while( (ch=getc(p1)) != EOF )
putc(ch, p2); /* Append the contents of first file to second file */
fclose(p1);
fclose(p2);
printf("\n After Merging (appending)
Contents of Second File \n");
p2=fopen("two.txt", "r");
while( (ch=getc(p2)) != EOF )
printf("%c", ch);
fclose(p2);
getch( );
}

INPUT/OUTPUT :

Enter the data for first file


CREC is accredited by NAAC.
Enter data for second file
This is CREC.
After Merging (appending) Contents of Second File
This is CREC. CREC is accredited by NAAC.

Writing integers to a file

Syntax :
putw(int w, FILE *fptr);
Eg. int x;
FILE *fptr;
putw(x, fptr);

Reading integers from a file

Syntax : getw(fptr);

-Write a program to read and print text file of integers. (or) Write a C program to create a file and write some
integers in that file and then read those integers from that file and display on the user screen.
#include <stdio.h>
main( )
{
int n, i, x;
FILE *p;
clrscr();
printf("\n Enter number of integers u want to put in the file : ");
scanf("%d", &n);
p = fopen("intfile.txt", "w"); /* Opening the file in write mode */
printf("\n Enter %d integers for the file \n", n);
for(i=0; i<n ; i++)
{
scanf("%d", &x); /* Take one integer from key board */
putw(x, p); /* Writing one integer in the file using putw( ) */
}
fclose(p);
printf(“\n Contents of the file \n”);
p = fopen("intfile.txt", "r"); /* Opening the file for reading */
while( (x=getw(p)) != EOF) /* Reading one integer from the file using getw( ) */
{
printf("%d \t",x);
}
fclose(p);
getch();
}
INPUT/OUTPUT : Enter number of integers u want to put in the file : 6
Enter 6 integers for the file
45 7 88 23 -12 25
Contents of the file
45 7 88 23 -12 25

NOTE : Even in this file "intfile.txt", last character is EOF character. After reading the last integer, if we try to
read next integer we will get EOF character. Like that condition in while loop becomes false.
- Write a program in C that reads the contents of a file containing integers and displays the largest among the
integers on the user screen.

#include <stdio.h>
main( )
{
int n, i, x, max= -999;
FILE *p;
clrscr();
printf("\n Enter number of integers u want to put in the file : ");
scanf("%d", &n);
p = fopen("intfile.txt","w"); /* Opening the file in write mode */
printf("\n Enter %d integers for the file \n", n);
for(i=0; i<n ; i++)
{
scanf("%d", &x);
putw(x, p); /* Writing one integer in the file */
}
fclose(p);
p = fopen("intfile.txt","r"); /* Opening the file for reading */
while( (x=getw(p)) != EOF) /* Reading one integer from the file */
{
if(x > max)
max=x;
}
fclose(p);
printf("\n Biggest integer in the file = %d", max);
getch();
}

INPUT/OUTPUT : Enter number of integers u want to put in the file : 7


Enter 7 integers for the file
2 44 12 -987 234 678 20
Biggest integer in the file = 678

Writing strings in a file


Syntax : fputs(string, FILE *fptr);
Eg. char str[40] = “Welcome” ;
fputs(str, fptr);

Reading strings from a file

Syntax : fgets( String variable, Max length of string variable, FILE *fptr );

/* PROGRAM FOR CREATING A FILE, WRITING STRING DATA


IN THAT FILE AND READING THE CONTENTS OF THE FILE */
#include<stdio.h>
#include<string.h>
main( )
{
FILE *fp;
char s[20];
clrscr();
printf("\n Enter few strings for the file \n");
fp=fopen("sfile.txt", "w"); /* Opening file in write mode */
while( strlen(gets(s)) > 0) /* gets( ) is for reading one string from keyboard */
{
fputs(s, fp); /* Writing one string in the file */
fputs("\n", fp); /* Writing one string i.e "\n" in the file */
}
fclose(fp); /* Closing the file */
printf("\n Contents of the file \n\n");
fp = fopen("sfile.txt", "r"); /* Opening file in read mode */
while( fgets(s, 20, fp) != NULL) /* Reading one string from the file */
printf(" \t %s", s);
fclose(fp);
getch();
}

INPUT/OUTPUT : Enter few strings for the file


Ravi
Kumar
CREC
Contents of the file
Ravi
Kumar
CREC

NOTE : while( strlen(gets(s)) > 0) : When we give a NULL string (i.e Pressing ‘Enter key’ ) while condition
becomes false since length of the NULL string is 0.
while( fgets(s, 20, fp) != NULL) : Reads one string from the file each time to the variable ‘s’. The last
string is NULL string. When reads this NULL string condition becomes false.

Formatted I/O operations using fprintf( ) and fscanf( ) functions.

fprintf( ) : By using this function, different types of data in the required format (i.e spaces etc.) can be
stored(writing) in the file at a time.

Syntax : fprintf(FILE *fptr, “control string”, list of variables);


Eg. int n=25;
float x=3.75;
char s[20] = “CREC”;
FILE *fptr;
fprintf(fptr, “\t%d %f \t %s \t”, n, x, s);

fscanf( ) : By using this function, different types of data from the file is read.

Syntax : fscanf(FILE *fptr, “control string”, list of variables);

Eg. fscanf(fptr, “%d%f%s”, &n, &x, s);


/* Illustration of Formatted I/O ‘fprintf’ and ‘fscanf’ functions */
#include <stdio.h>
main( )
{
FILE *fp;
char ch='y', s[80];
int a;
float b;
clrscr();
fp=fopen("test.txt", "w");
while(ch!='n')
{
printf("Enter a string,integer,and float value\n");
scanf("%s%d%f", s,&a,&b);
fprintf(fp,"%s %d %f \t ", s,a,b); /* write to file */
printf("\n To stop enter 'n' otherwise any other character : ");
fflush(stdin);
scanf("%c", &ch);
}
fclose(fp);
fp=fopen("test.txt","r");
while(fscanf(fp,"%s%d%f",s,&a,&b)!=EOF)
printf("\n%s,%d,%f", s,a,b);
fclose(fp);
getch();
}

INPUT/OUTPUT : Enter a string,integer,and float value


raghu 34 56.700001
To stop enter 'n' otherwise any other character : y
Enter a string, integer, and float value
raja 56 78.900002
To stop enter 'n' otherwise any other character : n
raghu 34 56.700001 raja 56 78.900002

Random Access of Files

So far, we have accessed the contents of the file in the sequential manner(if we want to read directly the
5 character in a file, it is not possible. First read 1st character, then 2nd , then 4th and the 5th character).
th

In C language we can access the file contents in random order also. If we want to read directly the 5th
character, then move the file pointer to the 5th position and read that character.

File positioning functions:

1. ftell( )
2. rewind( )
3. fseek( )

1. ftell( ) : tells (returns) the current position of the control in the file. At what position we are now in the
file.

Syntax : long int ftell(FILE *fptr);


Eg. long int x;
FILE *fptr;
x = ftell(fptr); File contents
C R E C I S I N T P T EOF
File position: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15

In the above example, ftell( ) returns 6.

2. rewind( ) : Resets the file position indicator to the beginning of the file. i.e control comes to the first
position of the file.

Syntax : rewind(FILE *fptr);

Eg. rewind(fptr);

3. fseek( ) : Sets the file position indicator to the required position of the file.

Syntax : fseek(FILE *fptr, long int offset, int whence);

Eg. FILE *fptr;


long int i;
int m;
fseek(fptr, i, m);
(1) whence(or position) must be one of the three values.
0 - Goto beginning of the file. Instead of 0 we can also mention SEEK_SET.
1 - stay at the current position. Instead of 1 we can also mention SEEK_CUR.
2 - Goto the end of the file. Instead of 2 we can also mention SEEK_END.

(1) offset – Specifies the number of positions(bytes) to be moved from the whence. If the offset value
is +ve then move forward. If the offset value is -ve then move backwards.

Eg. (1) fseek(fptr, 5, 0);


(i) whence = 0. Therefore goto the beginning of the file.
(ii) offset = 5. Therefore from that beginning position move forward by 5 positions.
Eg. (2) fseek(fptr, -7, 2);
(i) whence = 2. Therefore goto the end of the file. i.e to EOF character.
(ii) offset = -7. Therefore from that end position move backward by 7 positions.

C R E C I S I N T P T EOF
File position: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15

After execution of fseek(fptr, -3, 2);

C R E C I S I N T P T EOF
File position: 0 1 3 4 5 6 7 8 9 10 11 12 13 14 15

-Write a program in C that reverses the contents of a file and copies it into a new file. (or)
Write a program to display the contents of the file in reverse after copying in another file.

#include <stdio.h>
main( )
{
char ch;
int chars=0; /* ‘chars’ is for counting total no. of characters in the file */
long int i;
FILE *p1,*p2;
clrscr();
printf("\n Enter contents for data file\n");
p1=fopen("data.txt", "w");
while( (ch=getchar( )) != '$')
{
putc(ch, p1);
chars++;
}
fclose(p1);
p1=fopen("data.txt", "r");
p2=fopen("reverse.txt", "w");
for(i=1;i<=chars; i++)
{
fseek(p1, -i, 2); /* As offset is long int, 'i' is declared as long int */
ch=getc(p1); /* Take(Read) the character from file ‘data.txt’ */
putc(ch,p2); /* Write this character in the file ‘reverse.txt’ */
}
fclose(p1);
fclose(p2);
printf("\n Contents of Reverse file\n");
p2=fopen("reverse.txt", "r");
while( (ch=getc(p2)) != EOF)
printf("%c",ch);
fclose(p2);
getch();
}
INPUT/OUTPUT : Enter contents for data file
CREC is in Tirupati.It was started in 2004.
Contents of Reverse file
.4002 ni detrats saw tI.itapuriT ni si CERC
NOTE : fseek(p1,-i,2); Come to end of the file. From there move backwards by ‘i’ number of positions.

NOTE : feof( ) function returns true if end of file is reached, otherwise returns false.

Syntax : feof(fptr);
Differences between Text File and Binary File

Depending upon the way file is opened for processing, a file is classified into text file and binary file.
Working of binary files is similar to text files with few differences in opening modes, reading from file and
writing to file.

(1) (i) Opening modes of Text Files are r, w, a, r+, w+, a+.
(ii) Opening modes of binary files are rb, rb+, wb, wb+,ab and ab+.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk
respectively in case of binary files.

(2) Handling of newlines :

(i) In text mode, a newline character is converted into the carriage return-linefeed combination before
being written to the disk. Likewise, the carriage return-linefeed combination on the disk is converted
back into a newline when the file is read by a C program.
(ii) If a file is opened in binary mode, as opposed to text mode, these conversions will not take place.

(3) Representation of end of file

(i) In text mode, a special character, whose ASCII value is 26, is inserted after the last character in the
file to mark the end of file. If this character is detected at any point in the file, the read function
would return the EOF signal to the program.
(ii) There is no such special EOF character present in the binary mode files to mark the end of file. The
binary mode files keep track of the end of file from the number of character present in the directory
entry of the file.

(4) Storage of numbers

(i) In text file the numbers are stored as strings of characters. Thus, for eg. the integer 31912, even
though it occupies 2 bytes in main memory, when transferred to the disk it would occupy 5 bytes,
one byte per character(it treats each digit as one character). Thus, storing large amount of number
data in a disk file using text mode may be inefficient.
(iii) In binary mode, the integer 31912 will occupy 2 Bytes in Main memory and also in the disk. This
mode uses the functions fread() and fwrite() to read and write in the file.

Writing records(structures) in a File using fwrite( ) function.

fwrite( ) :
To write records(structures) in a file fwrite( ) function is used. Here file has to be opened in binary
mode.

Syntax : fwrite(void *Buffer, int size, int Count, FILE *ptr); (or)
fwrite(&Structure variable name, sizeof(structure variable), Number of records we want to write,FILE *fptr);

fread( ) :
To Read records(structures) from a File using fread( ) function. Here file has to be opened in binary
mode. Returns no. of records read.

Syntax :

int fread(void *Buffer, int size, int Count, FILE *ptr); (or)

fread(&Structure variable name, sizeof(structure variable), Number of records we want to write,FILE *fptr);

- Write a C program to create a file and write some structures(records) in that file and then read those records
and and display on the user screen. (or) Write a C program to illustrate fwrite() and fread() functions. (or)
Write a C program that displays the attributes of a file which contains records (structures).

#include<stdio.h>
main()
{
struct student
{
int roll;
char name[25];
float marks;
};
FILE *fp;
char ch;
struct student s;
clrscr();
fp = fopen("student.dat","w");
do
{
printf("\nEnter Name,RollNo,Marks \n");
fflush(stdin);
gets(s.name);
scanf("%d%f",&s.roll,&s.marks);
fwrite(&s, sizeof(s),1, fp); /* Writing one record in a file */
printf("\nDo you want to add another data (y/n) : ");
fflush(stdin);
scanf("%c",&ch);
} while(ch=='y');
fclose(fp);
printf("\n\tRoll\tName\tMarks\n");
fp=fopen("student.dat","r");
while(fread(&s,sizeof(s),1,fp)>0)
printf("\n\t%s\t%d\t%f",s.name,s.roll,s.marks);
fclose(fp);
getch( );
}
INPUT/OUTPUT : Enter Name, RollNo, Marks
Rao
543
78
Do you want to add another data (y/n) : y
Enter Name, RollNo, Marks
Kumar
567
58
Do you want to add another data (y/n) : n

NOTE : fwrite(&s, sizeof(s),1, fp); : 1 – writing one record.

while(fread(&s, sizeof(s),1,fp) > 0) : In the above eg. , fread( ) brings one record from the file and
returns 1. Thus while condition is true. After reading two records, tries to read 3rd record. 3rd record is not
available. Hence the fread() function returns 0. Thus while condition becomes false.

-Write a program to read information about student records which contains name, RollNo, marks in 6 subjects
for n number of students. Write the data(records) of these students in a file. According to JNTUA rules, find the
class of each student find the class and write the result in the another file and display the result on the user
screen.

#include<stdio.h>
#include<string.h>
main()
{
struct student
{
int roll, marks[6];
char name[25], class[20];
};
FILE *p1,*p2;
int i, j, n, tot;
struct student s[60];
clrscr();
p1 = fopen("student.dat","wb");
printf("\n Enter number of students : ");
scanf("%d",&n);
for(i=0 ; i<n ; i++)
{
printf("\nEnter Name,RollNo,Marks in 6 subjects for student-%d\n",i+1);
fflush(stdin);
gets(s[i].name);
scanf("%d",&s[i].roll);
for(j=0;j<6;j++)
scanf("%d", &s[i].marks[j]);
fflush(stdin);
strcpy(s[i].class," ");
fwrite(&s[i],sizeof(struct student),1,p1);
}
fclose(p1);
p1=fopen("student.dat","r");
p2=fopen("results.dat","w");
for(i=0 ; i<n ; i++)
{
fread(&s[i],sizeof(struct student),1,p1);
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d",s[i].name,s[i].roll,s[i].marks[0],s[i].marks[1],
s[i].marks[2],s[i].marks[3],s[i].marks[4],s[i].marks[5]);
for(j=0;j<6;j++)
{
if(s[i].marks[j] < 40)
{
strcpy(s[i].class,"FAIL");
fwrite(&s[i],sizeof(s[i]),1,p2);
break;
}
else
{
tot=0;
for(j=0 ; j<6 ; j++)
tot = tot + s[i].marks[j];
if(tot>=360)
strcpy(s[i].class,"FIRST CLASS");
else
if(tot>=300)
strcpy(s[i].class,"SECOND CLASS");
else
strcpy(s[i].class,"THIRD CLASS");
fwrite(&s[i],sizeof(s[i]),1,p2);
}
}
}
fclose(p1);
fclose(p2);
p2=fopen("results.dat","r");
printf("\n \tName\tRoll No. Class\n\n");
for(i=0 ; i<n ; i++)
{
if(fread(&s[i],sizeof(struct student),1,p2) > 0)
printf("\n\t%s\t%d\t%s",s[i].name,s[i].roll,s[i].class);
}
fclose(p2);
getch();
}

INPUT/OUTPUT : Enter number of students : 2


Enter Name, RollNo, Marks in 6 subjects for student-1
Ramesh 546 77 88 95 67 47 80
Enter Name, RollNo, Marks in 6 subjects for student-2
Suresh 578 55 45 56 62 50 50
Name Roll No. Class
Ramesh 546 FIRST CLASS
Suresh 578 SECOND CLASS

Preprocessors :
Preprocessor is a program that processes the source code(i.e C file) before it goes through compilation
process. The C Preprocessors are identified by the presence of hash symbol(#) at the beginning of the line.

There are 3 types of preprocessor statements i.e the C preprocessor provides 3 types of facilities.

1. File inclusion i.e #include


2. Macro substitution or Macro expansion i.e #define
3. Conditional inclusion or Conditional compilation

1. File inclusion i.e #include :

#include<filename> or #include”filename” causes the entire contents of the filename to be included to


the source code( C file) at that point in the program.

Eg. #include<stdio.h>, #include”math.h”

2. Macro substitution i.e #define :

The C preprocessor will replace the macros with their definitions throughout the program.

General format or Syntax : #define <identifier> <constant>

Eg. #define PI 3.142

During thepreprocessing, the preprocessor replaces every occurrence of PI in the program with 3.142.

/* Example */

#include <stdio.h>
#define PI 3.142
main()
{
float a,p,r;
clrscr( );
printf("\n Enter the radius value : ");
scanf("%f",&r);
a=PI*r*r;
p=2*PI*r;
printf("\n Area = %f, Perimeter = %f", a,p);
getch();
}
INPUT/OUTPUT : Enter the radius value : 4.5
Area = 63.6255, Perimeter = 28.278

Macros with arguments :


Macros can have arguments as like as functions.
#include <stdio.h>
#define square(x) x*x
main()
{
int a;
clrscr();
a=64/square(4);
printf("\n a = %d", a);
getch();
}
OUTPUT : a = 64
NOTE : If the statement is #define square(x) (x*x) then output would be a= 4.

3. Conditional inclusion or Conditional compilation :

Using special preprocessing directives i.e #if, #elif, #else, #endif we can include or exclude parts of the
program according to various conditions.

You might also like