You are on page 1of 20

UNIT IV

C Preprocessor directives:
 Before a C program is compiled in a compiler, source code is processed
by a program called preprocessor. This process is called preprocessing.
 Commands used in preprocessor are called preprocessor directives and
they begin with “#” symbol.
Below is the list of preprocessor directives in C.

Syntax/Description 
Preprocessor  
 
Syntax:#define
Macro This macro defines constant value and can be any of the
basic data types.
Syntax:#include<file_name>
Header file
The source code of the file “file_name” is included in the main
inclusion
program at the specified place.
Syntax: #ifdef, #endif, #if, #else, #ifndef
Conditional
Set of commands are included or excluded in source program
compilation
before compilation with respect to the condition. 
Syntax:#undef
Other directives
#undef is used to undefine a defined macro variable.

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


#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);
}
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.
#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;
}

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”);
#endif
return 0;
}
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;
}
EXAMPLE PROGRAM FOR UNDEF IN C:
This directive undefines existing macro in the program.
#include <stdio.h>
#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);
}

FILES
What is file?
File is a collection of bytes that is stored on secondary storage devices like disk.
There are two kinds of files in a system. They are,
1. Text files (ASCII)
2. Binary files
 Text files contain ASCII codes of digits, alphabetic and symbols.
 Binary file contains collection of bytes (0’s and 1’s). Binary files are
compiled version of text files.
Difference between Text and binary Files

Basic file operations in C programming:


There are 4 basic operations that can be performed on any files in C language.
They are,
1. Opening/Creating a file
2. Closing a file
3. Reading a file
4. Writing in a file
5. 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,
mode Description
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 Text 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;
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);
do
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(!feof(q));
}
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.
Reading and Writing in a Binary File
A Binary file is similar to a text file, but it contains only large numerical data.
The Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements, number_of_elements,
pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite()
function. Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp)
{
fwrite(mytext, sizeof(char), strlen(mytext), bfp);
fclose(bfp);
}
#include<stdio.h>
#include<stdlib.h>

struct employee
{
char name[50];
char designation[50];
int age;
float salary
} employee;

int main()
{
int n, i, chars;
FILE *fp;
fp = fopen("employee.txt", "wb");

if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}
printf("Testing fwrite() function: \n\n");
printf("Enter the number of records you want to enter: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
printf("\nEnter details of employee %d \n", i + 1);
fflush(stdin);
printf("Name: ");
gets(employee.name);
printf("Designation: ");
gets(employee.designation);
printf("Age: ");
scanf("%d", &employee.age);
printf("Salary: ");
scanf("%f", &employee.salary);
chars = fwrite(&employee, sizeof(employee), 1, fp);
printf("Number of items written to the file: %d\n", chars);
}
fclose(fp);
return 0;
}
Expected Output:
Testing fwrite() function:

Enter the number of records you want to enter: 2

Enter details of employee 1


Name: Bob
Designation: Manager
Age: 29
Salary: 34000
Number of items written to the file: 1

Enter details of employee 2


Name: Jake
Designation: Developer
Age: 34
Salary: 56000
Number of items written to the file: 1
The syntax of fread() function is this:
fread() function is the complementary of fwrite() function. fread() function is
commonly used to read binary data. It accepts the same arguments as fwrite()
function does.
Syntax: size_t fread(void *ptr, size_t size, size_t n, FILE *fp);
The ptr is the starting address of the memory block where data will be stored
after reading from the file. The function reads n items from the file where each
item occupies the number of bytes specified in the second argument. On
success, it reads n items from the file and returns n. On error or end of the file,
it returns a number less than n.
Let's take some examples:
Example 1: Reading a float value from the file
int val;

fread(&val, sizeof(int), 1, fp);


This reads a float value from the file and stores it in the variable val.
Example 2: Reading an array from the file
int arr[10];

fread(arr, sizeof(arr), 1, fp);


This reads an array of 10 integers from the file and stores it in the variable arr.
Example 3: Reading the first 5 elements of an array
int arr[10];

fread(arr, sizeof(int), 5, fp);


This reads 5 integers from the file and stores it in the variable arr.
Example 4: Reading the first 5 elements of an array
int arr[10];

fread(arr, sizeof(int), 5, fp);


This reads 5 integers from the file and stores it in the variable arr.
Example 5: Reading the structure variable
struct student
{
char name[10];
int roll;
float marks;
};

struct student student_1;

fread(&student_1, sizeof(student_1), 1, fp);


This reads the contents of a structure variable from the file and stores it in the
variable student_1.
Example 6: Reading an array of structure
struct student
{
char name[10];
int roll;
float marks;
};

struct student arr_student[100];

fread(&arr_student, sizeof(struct student), 10, fp);


This reads first 10 elements of type struct student from the file and stores
them in the variable arr_student.
The following program demonstrates how we can use fread() function.
#include<stdio.h>
#include<stdlib.h>

struct employee
{
char name[50];
char designation[50];
int age;
float salary
} emp;

int main()
{
FILE *fp;
fp = fopen("employee.txt", "rb");

if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}

printf("Testing fread() function: \n\n");

while( fread(&emp, sizeof(emp), 1, fp) == 1 )


{
printf("Name: %s \n", emp.name);
printf("Designation: %s \n", emp.designation);
printf("Age: %d \n", emp.age);
printf("Salary: %.2f \n\n", emp.salary);
}

fclose(fp);
return 0;
}
Expected Output:
Testing fread() function:

Name: Bob
Designation: Manager
Age: 29
Salary: 34000.00

Name: Jake
Designation: Developer
Age: 34
Salary: 56000.00
fprintf() function #
Syntax: int fprintf(FILE *fp, const char *format [, argument, ...] );
fprintf() function is same as printf() but instead of writing data to the console, it
writes formatted data into the file. Almost all the arguments of fprintf() function
is same as printf() function except it has an additional argument which is a file
pointer to the file where the formatted output will be written. On success, it
returns the total number of characters written to the file. On error, it returns
EOF.
The following program demonstrates how to use fprintf() function.
#include<stdio.h>
#include<stdlib.h>

int main()
{
FILE *fp;
char name[50];
int roll_no, chars, i, n;
float marks;

fp = fopen("records.txt", "w");

if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}

printf("Testing fprintf() function: \n\n");

printf("Enter the number of records you want to enter: ");


scanf("%d", &n);
for(i = 0; i < n; i++)
{
fflush(stdin);
printf("\nEnter the details of student %d \n\n", i +1);

printf("Enter name of the student: ");


gets(name);

printf("Enter roll no: ");


scanf("%d", &roll_no);

printf("Enter marks: ");


scanf("%f", &marks);

chars = fprintf(fp, "Name: %s\t\tRoll no: %d\t\tMarks: %.2f\n",


name, roll_no, marks);
printf("\n%d characters successfully written to the file\n\n", chars);
}

fclose(fp);
return 0;
}
Expected Output:
Testing fprintf() function:

Enter the number of records you want to enter: 5

Enter the details of student 1

Enter name of the student: Tina


Enter roll no: 1
Enter marks: 45
37 characters successfully written to the file

Enter the details of student 2

Enter name of the student: Nina


Enter roll no: 5
Enter marks: 89

37 characters successfully written to the file

Enter the details of student 3

Enter name of the student: Tim


Enter roll no: 2
Enter marks: 49

36 characters successfully written to the file

Enter the details of student 4

Enter name of the student: Jim


Enter roll no: 8
Enter marks: 41

36 characters successfully written to the file

Enter the details of student 5

Enter name of the student: King


Enter roll no: 9
Enter marks: 59
37 characters successfully written to the file
fscanf() Function in C
The syntax of the function is:
Syntax: int fscanf(FILE *fp, const char *format [, argument, ...] );
fscanf() function is used to read formatted input from the file. It works just like
scanf() function but instead of reading data from the standard input it reads
the data from the file. In fact, most of the arguments of fscanf() function are
same as scanf() function, except it just needs an additional argument obviously
enough a file pointer. On success, this function returns the number of values
read and on error or end of the file it returns EOF or -1.
The following program demonstrates how to use fscanf() function to read
formatted data from a file.
#include<stdio.h>
#include<stdlib.h>

int main()
{
FILE *fp;
char name[50];
int roll_no, chars;
float marks;

fp = fopen("records.txt", "r");

if(fp == NULL)
{
printf("Error opening file\n");
exit(1);
}

printf("Testing fscanf() function: \n\n");


printf("Name:\t\tRoll\t\tMarks\n");
while( fscanf(fp, "Name: %s\t\tRoll no: %d\t\tMarks: %f\n"
, name, &roll_no, &marks) != EOF )
{
printf("%s\t\t%d\t\t%.2f\n", name, roll_no ,marks);
}

fclose(fp);
return 0;
}
Expected Output:
Name: Tina Roll no: 1 Marks: 45.00
Name: Nina Roll no: 5 Marks: 89.00
Name: Tim Roll no: 2 Marks: 49.00
Name: Jim Roll no: 8 Marks: 41.00
Name: King Roll no: 9 Marks: 59.00

Random Access To File

There is no need to read each record sequentially, if we want to access a


particular record.C supports these functions for random access file processing.
1. fseek()
2. ftell()
3. rewind()

fseek():
This function is used for seeking the pointer position in the file at the specified
byte.
Syntax: fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative.This is the number of bytes which
are skipped backward (if negative) or forward( if positive) from the current
position.This is attached with L because this is a long integer.
Pointer position:
This sets the pointer position in the file.

Value pointer position


0 Beginning of file.
1 Current position
2 End of file
Ex:
1) fseek( p,10L,0)
0 means pointer position is on beginning of the file,from this statement pointer
position is skipped 10 bytes from the beginning of the file.
2)fseek(p,-5L,1)
From this statement pointer position is skipped 5 bytes backward from the
current position.
ftell()
This function returns the value of the current pointer position in the file.The
value is count from the beginning of the file.
Syntax: ftell(fptr);
Where fptr is a file pointer.
rewind()
This function is used to move the file pointer to the beginning of the given file.
Syntax: rewind( fptr);
Where fptr is a file pointer.
Example program for fseek():
Write a program to read last ‘n’ characters of the file using appropriate
file functions(Here we need fseek() and fgetc()).
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("file1.c", "r");
if(fp==NULL)
printf("file cannot be opened");
else
{ printf("Enter value of n to read last ‘n’ characters");
scanf("%d",&n);
fseek(fp,-n,2);
while((ch=fgetc(fp))!=EOF)
{
printf("%c\t",ch);
}
}
fclose(fp);
getch();}

You might also like