0% found this document useful (0 votes)
39 views30 pages

Unit 5

Uploaded by

balaraju92466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views30 pages

Unit 5

Uploaded by

balaraju92466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Programming for Problem

Solving Using ‘C’


Unit-V

Files: Types of files, Modes of Operations, File input and


output, File Handling Functions, Random Access Functions,
Command Line Arguments, Preprocessor Directives

Ramdas Kapila, Assistant Professor, Dept. of CSE,NSRIT


Programming for Problem Solving Using ‘C’ Unit-V

Department of Computer Science & Engineering


Programming for Problem Solving using ‘C’
(Common for Civil, ECE, MECH, EEE, CSE, CSE (DS), CSE (AI &ML)

Unit V: Files 7 Hours

Files: Types of files, Modes of Operations, File input and output, File Handling Functions, Random
Access Functions, Command Line Arguments, Preprocessor Directives

FILES: A file represents a sequence of bytes on the disk. A File can be used to store a large volume of
data.
A file is a container in computer storage devices used for storing data.
Why files are needed?
When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file
using a few commands in C.
You can easily move your data from one computer to another without any changes.

Types of Files:
A C program uses four types of files as follows:

1. Source Code File


Page 2 of 30
Programming for Problem Solving Using ‘C’ Unit-V

This file includes the source code of the program.


The extension for these kind of files are '.c'. It defines the main and many more functions written in C.
main() is the starting point of the program. It may also contain other source code files.
2. Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions that are
shared between various source files.

Advantages of header files:


1. At times the programmer may want to use the same subroutines for different programs. To do this,
he would just compile the code of the subroutine once and link to the resulting object file in any file in
which the functionalities of this subroutine are required.

2. At times the programmer may want to change or add the subroutines and reflect those changes in all
the programs. For doing this, he will have to only change the source file for the subroutines, recompile
the source code and then recompile and re-link the program.

This tells us that including a header file will make it easier at all levels of the program. If we need to
modify anything then changes are made only in the subroutines after which all the changes will be
reflected.

Standard header files

C provides us with some standard header files which are available easily.

Common standard header files are:


i) string.h – used for handling string functions.
ii) stdlib.h – used for some miscellaneous functions.
iii) stdio.h – used for giving standardized input and output.
iv) math.h – used for mathematical functions.
v) alloc.h – used for dynamic memory allocation.
vi) conio.h – used for clearing the screen.

The header files are added at the start of the source code so that they can be used by more than one
function of the same file.
3. Object files
They are the files that are generated by the compiler as the source code file is processed.
These files generally contain the binary code of the function definitions.
The object file is used by the linker for producing an executable file for combining the object files
together. It has a '.o' extension.
4. Executable file
This file is generated by the linker.

Page 3 of 30
Programming for Problem Solving Using ‘C’ Unit-V

Various object files are linked by the linker for producing a binary file which will be executed directly.
They have an '.exe' extension.
When dealing with files, there are two types of files.
1. Text files
2. Binary files

1. Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as
Notepad. When you open those files, you'll see all the contents within the file as plain text. You can
easily edit or delete the contents. They take minimum effort to maintain, are easily readable, and
provide the least security and takes bigger storage space.

2. Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store
data in the binary form (0's and 1's). They can hold a higher amount of data, are not readable easily,
and provides better security than text files.

Modes of Operations
In programming, we may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console. The data to be displayed may be
very large, and only a limited amount of data can be displayed on the console, and since the memory is
volatile, it is impossible to recover the programmatically generated data again and again. However, if
we need to do so, we may store it onto the local file system which is volatile and can be accessed every
time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file system
through our C program. The following operations can be performed on a file.
1. Creation of the new file
2. Opening an existing file
3. Reading from the file
4. Writing to the file
5. Deleting the file

File input and output


A file represents a sequence of bytes on the disk where a group of related data is stored. File is created
for permanent storage of data. It is a readymade structure.

Page 4 of 30
Programming for Problem Solving Using ‘C’ Unit-V

In C language, we use a structure pointer of file type to declare a file.


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

Function description

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

fseek() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode
can be of following types,

How to write a TEST CASE Software Testing Tutorial

mode description

Page 5 of 30
Programming for Problem Solving Using ‘C’ Unit-V

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing
the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform reading and writing
on file. getc() and putc() are the simplest functions which can be used to read and write individual
characters to a file.
#include<stdio.h>
int main()
{
FILE *fp;
char ch;

Page 6 of 30
Programming for Problem Solving Using ‘C’ Unit-V

fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

// closing the file pointer


fclose(fp);
return 0;
}

Reading and Writing to File using fprintf() and fscanf()


#include<stdio.h>
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
Page 7 of 30
Programming for Problem Solving Using ‘C’ Unit-V

do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same file but in
different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be
printed on the console using standard printf() function.

Difference between Append and Write Mode


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write
in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in
deletion of any data already present in the file. While in append mode this will not happen. Append
mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in
Append(a) mode, the cursor is positioned at the end of the present data in the file.

STANDARD LIBRARY I/O FUNCTIONS FOR FILES:


The stdio.h header file contains several different I/O functions. The following are the categories of
standard I/O (or) Library functions for files.
1. File Open/Close
2. Formatting I/O
3. Character I/O
4. File Open/Close:
File Open(fopen): We must open a file before it can be read, write, or update. The fopen()
function is used to open a file. The syntax of the fopen() is given below.

Syntax: FILE *fp;

fp = fopen ("file_name", "mode");

Page 8 of 30
Programming for Problem Solving Using ‘C’ Unit-V

fopen is a standard function which is used to open a file.


If the file is not present on the system, then it is created and then opened.
If a file is already present on the system, then it is directly opened using this function.
fp is a file pointer which points to the type file.

Example 1: fopen("E:\\cprogram\\newprogram.txt","w");
In the above example the file newprogram.txt doesn’t exists it will create and opens in mode
‘w’ for writing.

Example 2: fopen("E:\\cprogram\\oldprogram.txt","r"); Opens the existing file oldprogram.txt for


reading in mode 'r'. File Opening Modes:
Whenever you open or create a file, you have to specify what you are going to do with
the file. A file in 'C' programming can be created or opened for reading/writing purposes. Following
are the different types of modes in 'C' programming which can be used while working with a file.

File Mode Description

r Open a file for reading. The file cannot be modified

w Open a file for writing. If a file is in writing mode, if file doesn't


exist then a new file is created. If a file is already present then all the
data inside the file is erased and it is opened for writing.

a Open a file in append mode. If a file is in append mode, then the file
is opened. The content within the file doesn't change.

r+ open for reading and writing from beginning

w+ open for reading and writing, overwriting a file

a+ open for reading and writing, appending to file

Page 9 of 30
Programming for Problem Solving Using ‘C’ Unit-V

Mode “r”: It is a read only mode, which means if the file is opened in r mode, it won’t allow you to
write and modify content of it.
Mode “w”: It is a write only mode. The fopen() function creates a new file when the specified file
doesn’t exist and if it fails to open file then it returns NULL.

Mode “a”: Using this mode Content can be appended at the end of an existing file.
Mode “r+”: You are allowed to read, write and modify the content of file opened in “r+” mode.
Mode “w+”: Same as mode “w” apart from operations, which can be performed; the file can be read,
write and modified in this mode.
Mode “a+”: Same as mode “a”; you can read and append the data in the file, however content
modification is not allowed in this mode.

File Close(fclose): We should always close a file whenever the operations on file are over. It means
the contents and links to the file are terminated.
C' provides the fclose() function to perform file closing operation. The fclose function takes a file
pointer as an argument. It returns 0 if close was successful and EOF (end of file) if there is an error has
occurred while file closing.
Syntax: fclose (file_pointer); Example: FILE *fp;
fp = fopen ("data.txt", "r"); fclose (fp);

FORMATTING I/O FUNCTIONS:


Formatting I/O functions supports read and write functions of files.The following are the formatting
I/O functions for files.
Read functions for files Write functions for files
scanf() printf()
fscanf() fprintf()
fgets() fputs()

1. scanf():The scanf () function reads formatted data from keyboard. Syntax:


scanf(“conversion_specifiers”, variable_adresses);
Eg: scanf ( “%d”, &age);

2. printf(): The printf () function writes formatted data to screen.


Syntax:printf(“conversion_specifiers”,variable_lists);
Eg: printf (“%d %d”, var1, var2);

Page 10 of 30
Programming for Problem Solving Using ‘C’ Unit-V

Example: #include <stdio.h>


void main ()
{
int age;
float percentage;
printf ("Enter your age: ");
scanf ("%d",&age);
printf ("Enter your percentage: ");

scanf ("%f",&percentage);
printf(“\n Age: %d \n Percentage: %f “,age, percentage);
getch();
}
Output:
Enter your Age: 25
Enter your percentage: 100
Age: 25
Percentage: 100

3. fscanf(): The fscanf() function is used to read set of characters from file. It reads a word from
the file and returns EOF at the end of file.
Syntax: fscanf(file_pointer, conversion_specifiers, variable_adresses);

Eg: fscanf (fp, “%d”, &age);


Where, fp is file pointer to the data type “FILE”.

4. fprinf():The fprintf() function is used to write set of characters into file. It sends formatted
output to a stream.
Syntax: fprintf(file_pointer, str, variable_lists);
Eg: fprintf (fp, “%s %d”, “var1”, var2); Example:
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>

Page 11 of 30
Programming for Problem Solving Using ‘C’ Unit-V

void main()
{
FILE *fp;
char str[80], str1[80];
fp = fopen("data.txt","w");
printf("Enter string to be written in a file: ");
fscanf(stdin, "%s", str); /*Read from keyboard */
fprintf(fp, "%s", str); /*Write str to file */
fclose(fp);
fp = fopen("data.txt","r");
fscanf(fp, "%s", str1); /* read a word from file and copy into str1 */
fprintf(stdout, "%s", str1); /* print str1 on screen */
getch();
}
Output:

5. fgets():The fgets() function reads a line of characters from file. It gets string from a stream.

Syntax: fgets(buffer, n, file_pointer);


Eg: fgets(text,200,fp);

6. fputs():The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax: fputs(str, file_pointer);


Eg: fputs("hello c programming",fp);

Example:
include<stdio.h>
void main()
Page 12 of 30
Programming for Problem Solving Using ‘C’ Unit-V

{
FILE *fp;
char file[12],text[50]; int i=0;
fp = fopen(“line.txt” ,”w”);
printf(“Enter text here : “);
scanf(“%s”, text);
fputs(text, fp );
fclose(fp);
fp = fopen(“line.txt”, “r”);
if(fgets(text,50,fp )!=NULL)
while(text[i]!='\0')
{
putchar(text[i]); i++;
}
fclose(fp ); getch();
}
Output:

CHARACTER I/O FUNCTIONS:


These functions read one character at a time from a text stream and writes one character at a time to a
text stream.
The following are the types of Character I/O functions:
fgetc()
fputc()
getchar()
putchar()

fgetc():The fgetc() function returns a single character from the file. It gets a character from the stream.
It returns EOF at the end of file.
Syntax: fgetc(file_pointer); Eg: c=fgetc(fp); Example:
#include <stdio.h>
int main ()

Page 13 of 30
Programming for Problem Solving Using ‘C’ Unit-V

{
FILE *fp = fopen("test.txt","r");
do
{
char c = fgetc(fp);
if (feof(fp))
break ;
printf("%c", c);
}
while(1);
fclose(fp);
return 0;
}

Output:

fputc():The fputc() function is used to write a single character into file.


Syntax: fputc(char, file_pointer);
Eg: fputc('a',fp);
Example:
#include<stdio.h>
int main()
{
int i = 0;
FILE *fp = fopen("output.txt","w");
char string[] = "good bye", received_string[20];
for (i = 0; string[i]!='\0'; i++)
fputc(string[i], fp); fclose(fp);
fp = fopen("output.txt","r");
fgets(received_string,20,fp);
Page 14 of 30
Programming for Problem Solving Using ‘C’ Unit-V

printf("%s", received_string);
fclose(fp);
return 0;
}

Output:

putchar():It transmits a single character to the standard output device (the computer screen). In case
you want to display more than one characters, use putchar() method in a loop.
Syntax: putchar(character variable);

getchar():This is a single character input function. getchar() reads a single character from the
standard input data stream, which is normally the keyboard. Since This function reads only single
character at a time. You can use this method in the loop in case you want to read more than one
character from the screen.
Syntax: character variable = getchar( );
Example:
#include <stdio.h>
void main( )
{
int c;
printf( "Enter a string :"); c = getchar( );
printf( "\nYou entered: "); putchar( c );
getch();
}

Output:
Enter a string Hello World
The string you entered is H

Page 15 of 30
Programming for Problem Solving Using ‘C’ Unit-V

Random Access Functions

In C language, the data stored in the file can be accessed in two ways:
1. Sequential Access
2. Random Access
If we want to read access record in the middle of the file and if the file size is too large sequential
access is not preferable. In this case, random access to file can be used, which allows to access any
record directly at any position in the file.

C supports three functions for random access file processing:


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

1. fseek()
This function is used for setting the file pointer at the specified byte.

Syntax
int fseek(FILE *fp, long displacement, int origin);

Here,
fp – file pointer

displacement – It denotes the number of bytes which are skipped nackward or forward from the
position specified in the third argument. It is a long integer which can be positive or negative

origin – It is the position relative to which the displacement takes place. It takes one of the
following three values.

Position
Constant Value

Page 16 of 30
Programming for Problem Solving Using ‘C’ Unit-V

SEEK_SET
0 Beginning of file

SEEK_CURRENT
1 Current position

SEEK_END
2 End of file

Consider below program to understand fseek() function


#include<stdio.h>
struct record
{
char nm[20];
int rno;
}s;
void main()
{
int n;
FILE *fp;
fp=fopen(“student.dat”,”rb”);
if(fp==NULL)
{
printf(“Error in opening file\n”);
}
printf(“Enter the record number to be read”);
scanf(“%d”,&n);
fseek(fp,(n-1)*sizeof(s),0); //skip n-1 record
fread(&s,sizeof(s),1,fp); //read the nth record
printf(“%s\t”,s.nm);
printf(“%d\t”,s.rno);
fclose(fp);
}
If we want to read the nth record we will skip n-1 records with fseek() function and place the position
pointer at the beginning of the nth record.

2. ftell()
This function returns the current position of the file position pointer. The value is counted from
the beginning of the file.

Syntax
long ftell(FILE *fp);
Page 17 of 30
Programming for Problem Solving Using ‘C’ Unit-V

Consider below program to understand ftell() function


#include<stdio.h>
struct record
{
char nm[10];
int rno;
}s;
void main()
{
FILE *fp;
fp=fopen(“student.dat”,”rb”);
if(fp==NULL)
{
printf(“Error in opening file\n”);
}
printf(“Position pointer in the beginning %ld\n”,ftell(fp));
while(fread(&s,sizeof(s),1,fp)==1)
{
printf(“Position pointer %ld\n”,ftell(fp));
printf(“%s\t”,s,nm);
printf(“%d\t”,s.rno);
}
printf(“Size of file in bytes is %ld\n”,ftell(fp));
fclos(fp);
}

3. rewind()
This function is used to move the file pointer to the beginning of the file. This function is useful
when we open file for update.
Syntax:
rewind(FILE *fp);
Here, fp is file pointer of type FILE
Consider below program to understand rewind() function
#include<stdio.h>
void main()
{
FILE *fp;
fp=fopen(“student.dat”,”rb+”);
if(fp==NULL)
{
printf(“Error in opening file\n”);
}
printf(“Position pointer %ld\n”,ftell(fp));
fseek(fp,0,2);
printf(“Position pointer %ld\n”,ftell(fp));
Page 18 of 30
Programming for Problem Solving Using ‘C’ Unit-V

rewind(fp);
printf(“Position pointer %ld\n”,ftell(fp));
fclose(fp);
}

Command Line Arguments

It is possible to pass some values from the command line to your C programs when they are executed.
These values are called command line arguments and many times they are important for your
program especially when you want to control your program from outside instead of hard coding those
values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the
number of arguments passed, and argv[] is a pointer array which points to each argument passed to the
program. Following is a simple example which checks if there is any argument supplied from the
command line and take action accordingly −
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with single argument, it produces the following result.
$./a.out testing

Page 19 of 30
Programming for Problem Solving Using ‘C’ Unit-V

The argument supplied is testing


When the above code is compiled and executed with a two arguments, it produces the following result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it produces the
following result.
$./a.out
One argument expected
It should be noted that argv[0] holds the name of the program itself and argv[1] is a pointer to the first
command line argument supplied, and *argv[n] is the last argument. If no arguments are supplied, argc
will be one, and if you pass one argument then argc is set at 2.
You pass all the command line arguments separated by a space, but if argument itself has a space then
you can pass such arguments by putting them inside double quotes "" or single quotes ''. Let us re-write
above example once again where we will print program name and we also pass a command line
argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] )
{
printf("Program name %s\n", argv[0]);
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by space but inside
double quotes, it produces the following result.
$./a.out "testing1 testing2"
Program name ./a.out
Page 20 of 30
Programming for Problem Solving Using ‘C’ Unit-V

The argument supplied is testing1 testing2

Properties of Command Line Arguments:


1. They are passed to main() function.
2. They are parameters/arguments supplied to the program when it is invoked.
3. They are used to control program from outside instead of hard coding those values inside
the code.
4. argv[argc] is a NULL pointer.
5. argv[0] holds the name of the program.
6. argv[1] points to the first command line argument and argv[n] points last argument.

Note : You pass all the command line arguments separated by a space, but if argument itself has a
space then you can pass such arguments by putting them inside double quotes “” or single quotes ”.

// C program to illustrate
// command line arguments
#include<stdio.h>
int main(int argc,char* argv[])
{
int counter;
printf("Program Name Is: %s",argv[0]);
if(argc==1)
printf("\nNo Extra Command Line Argument Passed Other Than Program Name");
if(argc>=2)
{
printf("\nNumber Of Arguments Passed: %d",argc);
printf("\n----Following Are The Command Line Arguments Passed----");
for(counter=0;counter<argc;counter++)
printf("\nargv[%d]: %s",counter,argv[counter]);
}
return 0;
}

Output in different scenarios:


Page 21 of 30
Programming for Problem Solving Using ‘C’ Unit-V

1. Without argument: When the above code is compiled and executed without passing any
argument, it produces following output.
$ ./a.out
Program Name Is: ./a.out
No Extra Command Line Argument Passed Other Than Program Name

2. Three arguments : When the above code is compiled and executed with a three arguments, it
produces the following output.
$ ./a.out First Second Third
Program Name Is: ./a.out
Number Of Arguments Passed: 4
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First
argv[2]: Second
argv[3]: Third

3. Single Argument : When the above code is compiled and executed with a single argument
separated by space but inside double quotes, it produces the following output.
$ ./a.out "First Second Third"
Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----
argv[0]: ./a.out
argv[1]: First Second Third

4. Single argument in quotes separated by space : When the above code is compiled and executed
with a single argument separated by space but inside single quotes, it produces the following
output.

$ ./a.out 'First Second Third'


Program Name Is: ./a.out
Number Of Arguments Passed: 2
----Following Are The Command Line Arguments Passed----

Page 22 of 30
Programming for Problem Solving Using ‘C’ Unit-V

argv[0]: ./a.out
argv[1]: First Second Third

Preprocessor Directives
In C programming language, preprocessor directive is a step performed before the actual source code
compilation. It is not part of the compilation. Preprocessor directives in C programming language are
used to define and replace tokens in the text and also used to insert the contents of other files into the
source file.

When we try to compile a program, preprocessor commands are executed first and then the program
gets compiled.

Every preprocessor command begins with # symbol. We can also create preprocessor commands with
parameters.
Below is the list of preprocessor directives that C programming language offers.

Syntax/Description

Preprocessor

Syntax: #define
This macro defines constant value and can be any of
Macro the basic data types.

Syntax: #include <file_name>


Header file The source code of the file “file_name” is included
inclusion in the main program at the specified place.

Syntax: #ifdef, #endif, #if, #else, #ifndef


Set of commands are included or excluded in source
Conditional program before compilation with respect to the
compilation condition.

Syntax: #undef, #pragma


#undef is used to undefine a defined macro variable.
#Pragma is used to call a function before and after
Other directives main function in a C program.

Page 23 of 30
Programming for Problem Solving Using ‘C’ Unit-V

A program in C language involves into different processes. Below diagram will help you to understand
all the processes that a C program comes across.

All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and
for readability, a preprocessor directive should begin in the first column. The following section lists
down all the important preprocessor directives −

Sr.No. Directive & Description

1 #define
Substitutes a preprocessor macro.

2 #include
Inserts a particular header from another file.

3 #undef
Undefines a preprocessor macro.

4 #ifdef
Returns true if this macro is defined.

5 #ifndef
Returns true if this macro is not defined.

6 #if
Tests if a compile time condition is true.

7 #else
The alternative for #if.

8 #elif
#else and #if in one statement.

9 #endif

Page 24 of 30
Programming for Problem Solving Using ‘C’ Unit-V

Ends preprocessor conditional.

10 #error
Prints error message on stderr.

11 #pragma
Issues special commands to the compiler, using a standardized method.

Following are the preprocessor commands in C programming language...


#define
#define is used to create symbolic constants (known as macros) in C programming language. This
preprocessor command can also be used with parameterized macros.
Example Program
#include<stdio.h>
#include<conio.h>
#define PI 3.14
#define SQR(x) x*x //Parameterized Macro
void main()
{
double radius, area ;
clrscr() ;
printf("Enter the radius: ");
scanf("%ld",&radius);
area = PI * SQR(radius) ;
printf("area = %ld",area);
getch();
}
Output:

Page 25 of 30
Programming for Problem Solving Using ‘C’ Unit-V

EXAMPLE PROGRAM FOR #DEFINE, #INCLUDE PREPROCESSORS IN C LANGUAGE:


#define – This macro defines constant value and can be any of the basic data types.
#include <file_name> – The source code of the file “file_name” is included in the main C program
where “#include <file_name>” is mentioned.

#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

OUTPUT:

value of height : 100


value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?

EXAMPLE PROGRAM FOR CONDITIONAL COMPILATION DIRECTIVES:


A) EXAMPLE PROGRAM FOR #IFDEF, #ELSE AND #ENDIF IN C:
“#ifdef” directive checks whether particular macro is defined or not. If it is defined, “If” clause
statements are included in source file.
Otherwise, “else” clause statements are included in source file for compilation and execution.

Page 26 of 30
Programming for Problem Solving Using ‘C’ Unit-V

#include <stdio.h>
#define RAJU 100
int main()
{
#ifdef RAJU
printf("RAJU is defined. So, this line will be added in " \
"this C file\n");
#else
printf("RAJU is not defined\n");
#endif
return 0;
}

OUTPUT:

RAJU is defined. So, this line will be added in this C file

B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:


#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, “If” clause
statements are included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.

#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program”);

Page 27 of 30
Programming for Problem Solving Using ‘C’ Unit-V

#endif
return 0;

OUTPUT:

SELVA is not defined. So, now we are going to define here

C) EXAMPLE PROGRAM FOR #IF, #ELSE AND #ENDIF IN C:


“If” clause statement is included in source file if given condition is true.
Otherwise, else clause statement is included in source file for compilation and execution.

#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}

OUTPUT:

This line will be added in this C file since a = 100

EXAMPLE PROGRAM FOR UNDEF IN C LANGUAGE:


This directive undefines existing macro in the program.

#include <stdio.h>

Page 28 of 30
Programming for Problem Solving Using ‘C’ Unit-V

#define height 100


void main()
{
printf("First defined value for height : %d\n",height);
#undef height // undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}

OUTPUT:

First defined value for height : 100


value of height after undef & redefine : 600

EXAMPLE PROGRAM FOR PRAGMA IN C LANGUAGE:


Pragma is used to call a function before and after main function in a C program.

#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \ "main function" ) ;"

Page 29 of 30
Programming for Problem Solving Using ‘C’ Unit-V

OUTPUT:

Function1 is called before main function call


Now we are in main function
Function2 is called just before end of main function

X
Ramdas Kapila
Assistant Professor, NSRIT

Page 30 of 30

You might also like