PC Unit 5
PC Unit 5
ERROR HANDLING
INTRODUCTION TO PRE-PROCESSOR
MISCELLANEOUS DIRECTIVES
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
PART – A (2 Marks)
feof: The feof() function is used to check whether the file pointer is at the end-of-file
or not. It takes the file pointer as the argument and returns non-zero if the file pointer
is at the end-of- file. Otherwise it returns zero.
Syntax: feof(fp);
Example: if(feof(fp1))
printf(“\nend of file”);
ferror: The ferror() function reports the status of the file indicated. It also takes a
FILE pointer as its only argument and returns a non zero integer if an error has been
detected up to that point, during processing. It returns zero otherwise.
Syntax: ferror(fp);
Example: if(ferror(fp1) !=
0) printf(“\nerror has
occured”);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Random access file only access the file at the point at which the data should be read or
written , rather than having to process it sequentially.
The Functions
9. Define Pre-processor.
This is microprocessor program that processes the source program before it is
compiled. It is a collection of special statements called pre-processor statements or
pre-processor directives.
These directives are executed before the c program passes through the compiler.
Function Operation
Name s
fopen() Creates a new file for use. Opens an existing file for
use.
fclose() Closes a file which has been opened for use.
fgetc() Reads a character from a file.
fputc() Writes a character to the file.
fprintf() Writes set of data values to a file.
fscanf() Reads a set of data values from a file.
getw() Reads an integer from a file.
putw() Writes an integer to a file.
fseek() Sets the position to desired position in the file.
ftell() Gives the current position in the file.
rewind() Sets the position to the beginning of the file
fgets() Reads a string from the file
fputs() Writes a string to the file.
fread() Reads unformatted data from the file
fwrite() Writes unformatted data to the file
Example:
Beginning
fseek(fptr,5L,0);
5 byte
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
It is the first type. This directive is used for including one or more files in the
program. It instructs the compiler to make a copy of specified file to be included
in place of the directive.
Syntax #include<filename>
#include“filename”
Description filename–name of the file that can be included in our
source program
“filename”-searches file in current directories and then in
standard directives.
< > - search only in standard directives
Example #include<stdio.h> contains standard I/O functions
in directories
#include”loop.c” written by the user.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
#ifndef checks whether the given token has been #defined earlier in the file or in an
included file; if not, it includes the code between it and the closing #else or, if no #else
is present, #endif statement. #ifndef is often used to make header files idempotent by
defining a token once the file has been included and checking that the token was not
set at the top of that file.
17. Give the syntax of fopen().
Assigned as
an identifier to
the FILE
Each line ends with a newline character There are no lines or newline character
Data is read in forward direction only. Data may be read in any direction.
Data is converted into the internal format Data stored in file are in same format
before being stored in memory that they are stored in memory.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
It reads a single character from a given input stream and returns the
corresponding integer value (typically ASCII value of read character) on success. It
returns EOF on failure.
Syntax:
int getc(FILE *stream);
Example:
// Example for
getc() #include
<stdio.h>
int main()
{
printf("%c",
getc(stdin));
return(0);
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
getchar():
getchar() is a function call: it reads in a single character and waits for the user to
hit 'enter key' before reading the character.
Syntax:
int getchar(void);
Example:
// Example for
getchar() #include
<stdio.h>
int main()
{
printf("%c",
getchar()); return
0;
}
46. Write a simple program to read the numbers from the file and display numbers.
#include<stdio.h#
include<conio.h>
void main()
{
FILE *f1;
int
number,i;
clrscr();
printf("Contents of DATA file\n\n");
f1 = fopen("DATA","w"); /* create
a data file */ for(i=1;i<=30;i++)
{
scanf("%d",&num
ber); if(number==-
1)break;
putw(number,f1);
}
fclose(f1);
f1 = fopen("DATA","r");
while((number = getw(f1)) != EOF) /* Read from Data file */
{
if(number%2=
=0)
putw(number,f
1); fclose(f1);
getch();
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
47.Define Structure in C.
C supports a constructed data type known as structures, a mechanism for
packing data of different types. A structure is a convenient tool for handling a group
of logically related data items. This is known as Structure.
Arrays Structures
1. An array is a collection of 1. Structure can have elements of
related data elements of different types
same type.
2. An array is a derived data 2. A structure is a
type programmer- defined data
type
3. Any array behaves like a 3. But in the case of structure,
built-in data types. All we have first we have to design and
to do is to declare an array declare a data structure before the
variable and use it. variable of that type are declared
and used.
…….
Structure_member n;
}; v1,v2,…,vn;
Syntax:
typedef int numbers;
eg: numbers num1,num2;
In this example, num1 and num2 are declared as int variables.
The main advantage of user defined data type is that it increases the program‟s readability.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Enumerated type:
This is also a user defined data type. “Enum” is the keyword and “identifier” is the
user defined data type that is used to declare the variables. It can have any value
enclosed within the curly braces.
Syntax:
enum identifier {value1,value2, value 3,…}
For example:
enum day
{January,February,March,April,..}; enum
day month_st,month_end;
61.Define Union?
Unions are same as structures except that they differ in storage. Unions have
members of different data types. All the members of a union share the same storage
area within the memory. At any time only one value can be stored.
union exam
{
introll_no;
char name[15];
int mark1,mark2,mark3;
};
Nesting of structures are nothing but structure within another structure (i.e., a
structure can contain one or more structures embers).
A structure may be defined and/or declared inside another structure.
struct employee
{
int empno; char
name[15];
struct dob
{
int date ,
int month, int
year;
} d;
}emp;
DECLARATION OF STRUCTURES
It contains data members and each is accessed by the structure variable. A
structure is declared using the keyword struct followed by a structure name. All
the variables of the structures are declared within the structure.
structure_element n;
};struct structure_name v1,v2,…,vn;
Example:
struct student
{
int marks;
float avg;
char grade;
};
The structure definition does not allocate any memory. Structure provides a model
of how the structure is to be in memory and gives details of the member names.
Memory is allocated for the structure when we declare a variable of the structure.
struct student
{
int marks;
float avg;
char grade;
}s; // Declaring Structure Variable
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
int marks
av
float g
char grade
INITIALIZATION OF STRUCTURES
Initializing a structure means assigning some constants to the members of the
structure. The
initializes are enclosed in braces and are separated by commas.
Example:
struct student
{
int r_no;
char name[20]; char course[20]; float fees;
}struct student stud1 = {01, “Rahul”, “IT”, 45000};
Syntax:
struct_var.member_name;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Example:
stud1.rno = 01;
strcpy(stud1.name, “Kalam”);
stud1.course = “IT”;
stud1.fees = 45000;
Selecting a member from a structure pointer happens frequently, it has its own
operator -> which acts as follows. Assume that stud1 is a pointer to a structure of
type student we would refer to the name member as
stud1.rno->name
#include<stdio.h>
#include<conio.h>
struct student
{
int rollno;
char name[80]; float fees;
char DOB[80];
};
int main()
{
struct student stud1;
clrscr( );
printf(“\n Enter the roll number : “);
scanf(“%d”, &stud1.rollno);
printf(“\n Enter the name : “);
scanf(“%s”, stud1.name);
printf(“\n Enter the fees : “);
scanf(“%f”, &stud1.fees);
printf(“\n Enter the DOB : “);
scanf(“%s”, stud1.DOB);
printf(“\n ********STUDENT‟S DETAILS *******”);
printf(“\n ROLL No. = %d”, stud1.rollno);
printf(“\n NAME. = %s”, stud1.name);
printf(“\n FEES = %f”, stud1.fees);
printf(“\n DOB = %s”, stud1.DOB);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
getch( );
}
OUTPUT:
Enter the roll number: 101
Enter the name: Rahul
Enter the fees: 45000
Enter the DOB: 11.2.1995
********STUDENTÆS DETAILS *******
ROLL No. = 101
NAME. = Rahul
FEES = 45000.000000
DOB = 11.2.1995
2.ARRAYS OF STRUCTURES
An array of structures is the same way as we declare an array of built-in data type.
The array of structures can be used when common structure definition is need for
the process of information.
Syntax
Example
struct student stud[30];
Now, to assign values to the ith student of the class, we will write,
stud[i].r_no = 09;
stud[i].name = “RAM”;
stud[i].course = “CSE”;
stud[i].fees = 60000;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
3.NESTED STRUCTURES
A structure can be placed within another structure. That is, a structure may contain
another structure as its member. Such a structure that contains another structure
as its member is called a nested structure.
Example:
/*Program to read and display the information of student using nested Structure*/
#include<stdio.h>
#include<conio.h>
struct DOB
{
int day;
int month;
int year;
};
struct student
{
int roll_no;
char name[100];
float fees;
struct DOB date;
};
int main( )
{
struct student stud;
clrscr( );
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
OUTPUT:
Example:
#include<stdio.h>
struct employee
{
char name[20];
struct address
{
char city[20];
int pin;
char phone[14];
}add;
};
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,&emp.add.city, &emp.add.pin, &emp.add.pon
e);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,
emp.add.city, emp.add.pin,emp.add.phone);
}
OUTPUT
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
For example;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
struct employee
{
int empno;
char
empname[20];
float salary;
} emp;
employ(emp.empno)
employ(emp.empname)
employ(emp.salary);
Example
#include <stdio.h>
int add(int, int) ; //function declaration
int main()
{
//structures declartion
struct addition{
int a, b;
int c;
}sum;
printf("Enter the value of a : ");
scanf("%d",&sum.a);
printf("\nEnter the value of b : ");
scanf("%d",&sum.b);
sum.c = add(sum. a, sum.b); //passing structure members as arguments to
function
printf("\nThe sum of two value are : ");
printf("%d ", sum.c);
return 0;
}
//Function definition
int add(int x, int y)
{
int sum1;
sum1 = x + y;
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
return(sum1);
}
Output
Enter the value of a 10
Enter the value of b 20
The sum of two values 30
Example
#include<stdio.h>
struct date{
int day;
char month[10];
int year;
};
int main(){
struct date d;
printf("enter the day,month and year:");
scanf("%d%s%d",&d.day,d.month,&d.year);
display(&d);
return 0;
}
void display(struct date *p){
printf("day=%d\n",p->day);
printf("month=%s\n",p->month);
printf("year=%d\n",p->year);
}
OUTPUT
enter the day, month and year:20 MAR 2021
day=20
month=MAR
year=2021
In this method, the entire structure is passed as an argument to the function, since
the function is working on a copy of the structures, any changes made to the
structure members within the function are not reflected in the original structure.
Therefore, it is necessary for the function to return the entire structure back to the
calling function.
Example:
#include<stdio.h>
void employ(struct employee emp);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
struct employee
{
int empno;
char empname[20];
};
main()
{
struct employee emp1;
printf(“\nEnter Employee No. and Name : “);
scanf(“%d%s”,&emp1.empno,emp1.empname);
employ(emp1);
}
OUTPUT:
Example:
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
void display(struct student);
int main()
{
int i;
struct student st;
printf("Enter Records of students");
printf("\nEnter Rollno:");
scanf("%d",&st.rollno);
printf("\nEnter Name:");
scanf("%s",&st.name);
display(st);
getch();
return 0;
}
Void display(struct student st)
{
printf("\nStudent Information List:");
printf("\nRollno:%d, Name:%s",st.rollno,st.name);
}
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
OUTPUT
Enter Records of students
Enter Rollno:
11
Enter Name:
Sonoo
Student Information List:
Rollno:11,
Name: Sonoo
struct student
{
char name[20];
int age;
};
struct student s1;
struct student
{
char name[20];
int age;
};
typedef struct student stud;
stud s1, s2;
Now we can use the stud variable in a program to create the variables of
type struct student.
The above typedef can be written as:
Example
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",s1.name);
printf("\nEnter the age of student:");
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
Output
Enter the details of student s1:
Enter the name of the student:
Peter
Enter the age of student:
28
Name of the student is : Peter
Age of the student is : 28
Example
#include <stdio.h>
//structures declaration
typedef struct addition{
int a, b;
}sum;
void add(sum) ; //function declaration with struct type sum
int main()
{
sum s1;
printf("Enter the value of a : ");
scanf("%d",&s1.a);
printf("\nEnter the value of b : ");
scanf("%d",&s1.b);
add(s1); //passing entire structure as an argument to function
return 0;
}
//Function Definition
void add(sum s)
{
int sum1;
sum1 = s.a + s.b;
printf("\nThe sum of two values are :%d ", sum1);
}
Output
• Enter the value of a 10
• Enter the value of b 20
• The sum of two values 30
ENUM
enum is another user-defined type consisting of a set of named constants
called enumerators.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Example
#include <stdio.h>
enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Sat
urday};
int main()
{
enum weekdays w; // variable declaration of weekdays type
w=Monday; // assigning value of Monday to w.
printf("The value of w is %d",w);
return 0;
}
Output
The value of w is 2
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Example
#include <stdio.h>
enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum days d;
d=monday;
switch(d)
{
case sunday:
printf("Today is sunday");
break;
case monday:
printf("Today is monday");
break;
case tuesday:
printf("Today is tuesday");
break;
case wednesday:
printf("Today is wednesday");
break;
case thursday:
printf("Today is thursday");
break;
case friday:
printf("Today is friday");
break;
case saturday:
printf("Today is saturday");
break;
}
return 0;
}
OUTPUT
Today is Monday
6.UNION
A union is a special data type available in C to store different data types in the
same memory location. We can define a union with many members, but only one
member can contain a value at a time. Unions provide an efficient way of using the
same memory location for multi-purpose.
DEFINITION
Defining a union, is very similar as like defining structure but keyword union is
used. The union statement defines a new data type, with more than one member
for your program.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Syntax:
union
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
union sample
{
int marks;
float avg;
char grade;
};
Memory allocation
In structure
struct student
{
int rollno;
char gender;
float marks;
};
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
In union
union student
{
int rollno;
char gender;
float marks;
};
#include <conio.h>
union number
{
int n1; float n2;
}union number x;
void main()
{
clrscr() ;
printf("Enter the value of n1: ");
scanf("%d", &x.n1);
printf("Value of n1 =%d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%d", &x.n2);
printf("Value of n2 = %d\n",x.n2);
}
Output:
Enter the value of n1:10
Value of n1 =10
Enter the value of n2:20.5
Value of n2 =20.50000
Definition:
A file is a collection of related data stored on a secondary storage device like
hard disk.
Every file contains data that is organized in hierarchy as fields, records, and
databases
Stored as sequence of bytes, logically contiguous (may not be physically
contiguous on disk).
Streams
Stream is a Sequence of data bytes, which is used to read and write data to
a file.
A Stream acts as an interface between a program and an input/output
Device.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Types of files
Text file or ASCII text file: It is a stream of characters that can be
processed sequentially and in forward direction only.
Binary file: It is collection of bytes.
Sequential File: Data is stored sequentially, to read the last record of
the file, we need to traverse all the previous records before it. Eg: files on
magnetic tapes.
Random Access File: Data can be accessed and modified randomly. We
can read any record directly. Eg: files on disks.
File attributes.
The various file attributes are:
Filename - String of characters to store the name of files.
File Position -Pointer that points the position at which next read and write
operation to be performed.
File Structure -It indicates whether file is text or binary file
File Access Methods- Indicates whether file can be accessed sequentially or
randomly
Attributes flag: Specifies that hidden or read-only or archive file.
File operations.
• Creating a new file
• Opening an existing file
• Reading from a file
• Writing to a file
• Moving to a specific location in a file (seek)
• Closing a file
FILE *fptr;
Purpose of opening the file (i.e., for reading or writing or appending etc.,)
or “rb+”
“w+b” Creates and opens binary file for read and write
operations.
or
“wb+”
“a+b” Opens a binary file for for read and write operations.
or “ab+”
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
CLOSING A FILE
fclose(fptr);
Example:
FILE *book;
book = fopen(“computer”, ”r”);
.
.
.
fclose(book);
Output
The content of the file will be printed.
fp=fopen(filename,"w");
for(i=1;i<=3;i++)
{
printf("Enter rno,name,average of student no%d:",i);
scanf("%d %s %f",&rno,name,&avg);
fprintf(fp,"%d %s %f\n",rno,name,avg);
}
fclose(fp);
Output:
Enter the filename:
test.txt
Enter rno,name,average of student no:1 101
ram 75
Enter rno,name,average of student no:2 102
Raj 79.4
Enter rno,name,average of student no:3 103
Rahul 92.3
1. putc()
2. getc()
3. getw()
4. putw()
5. fscanf()
6. fread()
7. fprintf()
8. fwrite()
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Syntax: putc(c,fptr);
This function operates on file that is opened in reading mode. Reads a single
character from the file.
Syntax: getc(fptr);
Reads character from file pointed by file pointer fp and displays on it screen. Now
file pointer moves by one character position for every getc() function and returns
EOF (end-of-file). EOF is a constant that indicates the end-of-file reached on a
file. To get character from a file terminating character (^z) is entered.
FILE *f1;
char c;
printf("Data Input\n\n");
f1 = fopen("INPUT", "w");
while((c=getchar()) != EOF)
putc(c,f1);
fclose(f1);
printf("\nData Output\n\n");
f1 = fopen("INPUT","r");
while((c=getc(f1)) != EOF)
printf("%c",c);
fclose(f1);
Output:
Data Input
Data Output
This is a program to test the file handling features on this system
putw and getw are integer oriented functions. They are similar to the getc and putc
functions and are used to read and write an integer.
(i) Integer input function - putw()
Syntax: putw(integer, fptr);
This function is used to write integer value on file pointed by file pointer.
Syntax: getw(fptr);
Syntax: fgets();
gets() function with the argument sachin can receive a string of maximum 20
characters as a single string.
The string may/may not include spaces in between them.
The puts function with the arguments displays the string in the standard output
device which is received previously by using the gets() function.
3. MIXED DATA I/O FUNCTIONS FOR FILE
The function printf() and scanf() are used for performing Input/Output operations
in the file (Without involving file). Similar to scanf() and printf() functions.
(i) File input function -fscanf()
fscanf() is used to perform input operations in files.
Screen
#include<stdio.h>
void main()
ch;
printf("\n\t*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
*"); fp=fopen("textfile.txt","w");
if(fp==NULL)
else
while((ch=getchar())!=EOF)
putc(ch,fp);
}
printf("\nFile Content saved in textfile.txt");
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
fclose(fp);
fp=fopen("textfile.txt","r");
printf("\n The content read from file and display on the screen");
printf("\n \n");
while((ch=getc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
getch();
Output:
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
^Z
fread() - This function reads data from stream of any data type.
Syntax
size_t fread(void *ptr, size_t size,size_t n, FILE *fp);
fwrite()
This function writes to a stream or specified file. The syntax for fwrite() is
Syntax
size_t fwrite(const void *ptr,size_t size,size_t n,FILE *fp);
The feof() function is used to check whether the file pointer is at the end-of-
file or not. It takes the file pointer as the argument and returns non-zero if the
file pointer is at the end-of- file. Otherwise it returns zero.
The ferror() function reports the status of the file indicated. It also takes a FILE
pointer as its only argument and returns a non zero integer if an error has been
detected up to that point, during processing. It returns zero otherwise.
Sequential Files are generally used in cases where the program processes the data
in a sequential fashion.
Eg: counting words in a text file
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
To access a particular part of a file randomly and not in reading the other parts.
This is done by using the I/O library functions, namely
1. fseek()
2. ftell()
3. rewind()
4. fseek() FUNCTION
The fseek() function allows us to read from or write to any point in the stream of
bytes opened by using the fopen() function. It is used to move the position of the
file pointer to the desired location in the file.
1. fseek() FUNCTION
The fseek() function allows us to read from or write to any point in the stream of
bytes opened by using the fopen() function. It is used to move the position of the
file pointer to the desired location in the file.
fseek(fptr,5L,0)
;
5 byte
2. ftell() FUNCTION
Function returns the current position of the file pointer in the file.
Syntax
Example
3. rewind() FUNCTION
Function resets the file pointer to the beginning of the file.
Syntax
rewind(fptr);
Character
while(feof(fp) == 0)
putchar(getc(fp));
while(!fseek(fp,-2L,1));
fclose(fp);
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z
ZYXWVUTSRQPONMLKJIHGFEDCBA
1. argc
2. argv
1. Argument argc
2. Argument argv
The size of the array will be equal to the value of argc. Information contained
in command line is passed to program through these arguments whenever
main is called. The first parameter in command line is program name. Here
argv[0] represents the program name.
printf("\n\t*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*");
if(argc<3)
{
printf("\nAtleast Type 2 Numbers");
exit(1);
}
printf("\nThe sum is : ");
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
for(i=1;i<argc;i++)
sum = sum + atoi(argv[i]);
printf("%d",sum);
}
Program to copy the content of one file to another file using command line
arguments
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
FILE *fp1,*fp2;
int i,ch;
if(argc!=3)
{
printf("Program parameter missing");
exit(0);
}
fp1=fopen(argv[1],"r");
fp2=fopen(argv[2],"a");
while((ch=getc(fp1))!=EOF)
putc(ch,fp2);
printf("file %s is successfully copied",argv[1]);
Return(0);
}
14.PREPROCESSOR
Definition
The Preprocessor, as the name implies, is a program that processes the
source code before it passes through the complier. This is known as
preprocessor.
Important Points
• It operates under the control of preprocessor command lines or directives.
• Preprocessor directives are placed in the source program before the main line.
• Before the source code passes through the compiler, it is examined by the
preprocessor for any preprocessor directives.
• Preprocessor directives begin with the symbol # in column one and do not
require a semicolon at the end.
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Three Categories
i. Macro substitution directives
ii. File Inclusion directives
iii. Compiler control directives (or) Conditional inclusion directives
Syntax
The general form is
#define identifier string
Examples
Simple Macro Sub for Expressions
#define AREA 5 * 12.46
#define SIZE sizeof(int) * 7
#define TWO-PI 2.0 * 3.14
#define A (55 – 33)
#define B (55 + 33)
#define AND
#define PRINT printf(“Success”);
Note: The above statements are consider as, TEST AND PRINT
That will become
if (x>y) printf (“Success \n”);
Program
#include<stdio.h>
#define PIE 3.14
main()
{
float r=3,area;
area=2*r*PIE;
printf(“%f”,area);
getch();
}
or
#include <filename>
Example
#include <stdio.h>
#include “TEST.C”
Predefined Macros
ANSI C defines a number of macros. Although each one is available for your use in
programming, the predefined macros should not be directly modified.
Macro Description
Example
#include <stdio.h>
main()
{
printf("File :%s\n", FILE;
printf("Date :%s\n", DATE );
printf("Time :%s\n", TIME);
printf("Line :%d\n", LINE );
printf("ANSI :%d\n", STDC);
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Output
File :C:\Users\Documents\sample.c Date :Aug 5 2015
Time :19:03:18
Line :7
ANSI :1
15.MISCELLANEOUS DIRECTIVES:
There are two more pre-processor directives, though they are not very commonly
used.
They are #undef and #pragma
1. #undef
On some occasion, it may b desirable to cause a defined name to become
„undefined‟. This can be accomplished by means of the 3undef directive.
would cause the definition of PENTUM to be removed from the system. All
subsequent #ifdef PENTUM statements became false.
#include<stdio.h>
#define height 100
void main()
{
Output
First defined count value:100
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C
Sl Pragma Description
. command
n
o
1. #pragma startup This directive executes function named
“function_name_1”before starting of the program
<function_name_1
>
2. #pragma exit This directive executes function named
<function_name_2 “function_name_2”before termination of
> the program
3. #pragma warn-rvl If function doesn‟t return a value, then
warnings are suppressed by this directive while
compiling.
4. #pragma warm-par If function doesn‟t use passed function
parameter, then warnings are suppressed.
5. #pragma warn-rch If non-reachable code is written inside a
program, such warnings are suppressed by this
directive.
Height value after redefining:700
2. #pragma
A special directive we can turn on or off certain features. Pragma vary from
one compiles to another.
Example Program
#include<stdio.h>
int display();
#pragma startup display
#pragma exit display
int main()
{ printf("\nI am in main function");
return 0;
}
int display()
{
printf("\nI am in display function");
return 0;
}
Output:
Enter the filename:
test.txt
Sri Manakula Vinayagar Engineering College Unit – 5 Programming in C