Unit 9 File Handling
Unit 9 File Handling
Unit 9 File Handling
File Handling
Introduction: File
A file is a place on the disk where a group of related data is stored. File handling is a process of creating a new
file, append records in file and read records from file i.e. File handling in C provides the facility to store and
manipulate inputted or processed information in a file for further use.
The program that accepts the input data from the keyboard at the time of execution and writes output to the
VDU (visual display unit), such type of Input / Output is called console I/O. for the purpose we use printf(),
scanf(), getch(), getche(), getchar(), gets(), puts(), etc functions. It is fine for small amount of data. It has two
main problems:
It becomes very inconvenient and time consuming to handle the large volume of data through the
terminal.
The entire data is lost when either the program is terminated or the computer system is turned off.
Text files
A text file is a human-readable sequence of character and the words they form that can be encoded into
computer readable format such as ASCII. A text file contains only textual characters like alphabets, digits, and
special symbols with no special formatting such as underlining or displaying character in bold face or
different fonts. There is no graphical information, sound or video files. A text a file is also knows as ASCII
file can be read by any word processor. Text file stores information in consecutive characters. These
characters can be interpreted as individual data items or as component of strings or numbers.
A good example of a text file is any C program, say simple_interest.c
Binary files
A binary file is merely a collection of bytes. This collection might be a complied version of C program (say
simple_interest.exe).or music data stored in wave file or a picture stored in graphic file. It contains more than
plain text e.g. sound, image, graphics etc. a binary file made up of machine readable symbols that represents
1’s and 0’s. These files organize data in to block containing contagious bytes information.
Opening modes:
rb, rb+, wb, wb+, ab and ab+
------------------------------------------------------------------------------------------------------------------------------------------------
1 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
These two modes are not compatible. So any file written in text mode must be read back in the text mode
and in binary mode must be read in binary mode.
c) Storage of numbers:
In text mode, numbers are stored as string of characters. The number 32235 occupies 2 bytes in memory
but when it is written to disk using function fprintf(), it occupies 5 bytes. Similarly, 12345 occupy 4 bytes
in memory but 11 bytes in disk. I.e. in text mode, there is insufficient space on the disk, if large amount of
numerical data is to be stored.
In binary mode, there is sufficient space on the disk to store large amount of data. Each number would
occupy the same number of bytes on both memory and disk.
File Operations:
There are different operations that can be carried out on a file. These are:
a) Creation of a new file
b) Opening an existing file
c) Reading from a file
d) Writing to a file
e) Moving to a specific location in a file
f) Closing a file
Opening a file
To work with file using any file handling library functions, we have to declare the file using structure FILE.
The structure FILE is defined in <stdio.h> header file. It can be declared as:
A structure named FILE is defined in the file stdio.h that contains all the information about file like:
Name of file
Status
Buffer size
current position
end of file status
Before we can read or write information from or to a file on a disk we must open the file. To open a file
fopen() function is used.
Errors in fopen()
If an error occurs in opening a file, then fopen() returns NULL.
FILE *p;
p= fopen(“abc.txt”, ”r”);
if(p==NULL)
{
printf(“Error in opening file”);
exit(1);
}
------------------------------------------------------------------------------------------------------------------------------------------------
2 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
Errors may occur due to following reasons
If we try to open a file in read mode and If the file doesn’t exists or we do not have read permission
on that file.
If we try to create a file but there is no space on disk or we don’t have write permissions.
If we try to create a file that already exists and we don’t have permission to delete that file.
Operating system limits the number of files that can be opened at a time and we are trying to open
more files than that number.
The fgetc() reads the character from the current pointer position, advances the pointer position so that it now
points to the next character, and return the character that is read, which can be collected in the variable.
Closing a file
Once we have finished reading from the file, we need to close it. For this, we can use a function: fclose ().
Syntax: fclose (file_pointer);
Example: fclose (fp);
Once we close the file, we cannot read from it unless we reopen the file. When we close the file using fclose(),
three operations would be performed:
a) The characters in the buffer would be written to the file on the disk.
b) At the end of file a character with ASCII value 26 (EOF) would get written.
c) The buffer would be eliminated from memory.
Reading existing contents, writing new contents, modifying existing contents of the file i.e. for both
“r+” reading and writing
Syntax: filepointer = fopen(“filename”, “r+”);
Creates a text file for both reading and writing but if text file exist it just overwrites the contents.
“w+”
Syntax: filepointer = fopen(“filename”, “w+”);
Opens a text file for reading and writing preserving previous contents. Creates new file if the
“a+” specified file does not exist.
Syntax: filepointer = fopen(“filename”, “a+”);
rb Opens a binary file for reading. Syntax: filepointer = fopen(“filename”, “rb”);
------------------------------------------------------------------------------------------------------------------------------------------------
3 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
Creates a new binary file for writing but if the binary file exists, overwrites the contents.
wb
Syntax: filepointer = fopen(“filename”, “wb”);
Append mode either open an existing binary file for writing without overwriting the previous
ab contents or creates new binary file if the file does not exist.
Syntax: filepointer = fopen(“filename”, “ab”);
rb+ Open binary file for both reading and writing. Syntax: filepointer = fopen(“filename”, “rb+”);
Creates a binary file for both reading and writing but if binary file exist it just overwrites the
wb+ contents.
Syntax: filepointer = fopen(“filename”, “wb+”);
Opens a binary file for reading and writing preserving previous contents. Creates new binary file if
ab+ the specified file does not exist.
Syntax: filepointer = fopen(“filename”, “ab+”);
fprintf()
It is used to write set of characters into file. It sends formatted output to a stream.
Syntax: fprintf(file_pointer, “control strings”, arguments);
fscanf()
It is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.
Write a program to store employee information such as employee id, name, and salary entered by user
from console into the file.
#include<stdio.h>
#include<conio.h>
struct employee
{
int emp_id;
char name[40];
float salary;
};
void main()
{
FILE *fp;
struct employee e;
------------------------------------------------------------------------------------------------------------------------------------------------
4 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
clrscr();
fp=fopen("Employee.txt","w+");
if(fp==NULL)
{
printf("\n File doesn't exist");
return;
}
fputc()
It is used to write a single character into file. It outputs a character to a stream.
Syntax: int fputc(int char, FILE *stream);
Where
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
fgetc()
It is used to return a single character from the file. It gets a character from the stream. It return EOF at the end
of the file.
Syntax: fgetc(file_pointer);
------------------------------------------------------------------------------------------------------------------------------------------------
5 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
{
FILE *fp;
char c;
clrscr();
fp=fopen("employee.txt","r");
while((c=fgetc(fp))!=EOF)
printf("%c",c);
fclose(fp);
getch();
}
fseek()
It is used to set the file pointer to the specified offset. It is used to write data into file at desired location. This
function sets the file position indicator for the stream pointed to by stream or we can say it seeks a specified
place within a file and modify it. This function accepts three arguments: file stream, offset and whence. The
first argument: FILE stream pointer returned by the fopen() function, offset tells the amount of bytes to seek
and the third argument whence tells from where they seek of offset number of bytes is to be done. The
available values for whence are:
SEEK_SET Seeks from beginning of file
SEEK_CUR Seeks from current position
SEEK_END Seeks from end of file
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("myfile.txt","w+");
fputs("This is Example of fseek function ",fp);
fseek(fp,7, SEEK_SET);
fputs(" I Love Programming ",fp);
fclose(fp);
getch();
}
In above program, Initially program creates the file and writes This is Example of fseek function but later we
had reset the write pointer at 7th position from the beginning and used puts() statement which over-write the
file and provides following output.
Output:
This is I Love Programming
rewind()
It sets the file pointer at the beginning of the stream. It is useful if we have to use steam many times.
Syntax: rewind(file_pointer);
#include<stdio.h>
#include<conio.h>
------------------------------------------------------------------------------------------------------------------------------------------------
6 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("employee.txt","r");
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
rewind(fp);
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
getch();
}
ftell()
It returns the current file position of the specified stream. We can use this function to get the total size of a file
after moving file pointer at the end of the file. We can use SEEK_END constant to move the file pointer at the
end of file.
Syntax: ftell(file_pointer);
fwrite()
It is used to write binary data as well as text file to the file.
Syntax: size_t fwrite (const void *ptr, size_t size, size_t n, FILE*stream);
Remarks: fwrite appends a specified number of equal-sized data items to an output file.
Ptr = Pointer to any object; the data written begins at ptr
size = Length of each item of data
n =Number of data items to be appended
stream = file pointer
------------------------------------------------------------------------------------------------------------------------------------------------
7 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
Example 2: Writing an array
int num[5] = {100, 200, 40, 50, 890};
fwrite (num, sizeof(num),1,fp);
It will write only the first two elements of arrays into the file.
It will write the 0th and 1st element of the array into the file.
fread()
------------------------------------------------------------------------------------------------------------------------------------------------
8 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
It is commonly used to read binary data as well as text data too It has four arguments:
Address of the structure to be written to the disk
Size of structure in bytes
Number of structure that we want to write at a time
The pointer to the file, where we want to write.
Remarks: fread reads a specified number of equal-sized data items from an input stream into a block.
ptr = It is the reference of an array or structure where data will be stored after reading
size = it is the total number of bytes to be read from file
n = Number of times a record will be read.
stream = file pointer
It will read a float value from the file and stores it in the variable val.
It will read an array of 10 integers from the file and stores in the variable arr.
It will read 5 integers from the file and stores it in the variable arr..
It will read the contents of a structure variable from the file and stores it in the variable s.
It will read first 10 elements of type struct student from the file and stores them in the variable s.
------------------------------------------------------------------------------------------------------------------------------------------------
9 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
Examples related to fread() and fwrite():
Program 1:
#include<stdio.h>
#include<conio.h>
struct book
{
char name[50];
int page;
};
void main()
{
FILE *fp;
int i,n;
struct book b;
clrscr();
fp=fopen("Book.dat","wb+");
if(fp==NULL)
{
printf("\n File can't be opened");
exit(0);
}
printf("\n How many books:- ");
scanf("%d", &n);
printf("\n Input following records of %d books:- ",n);
for(i=0;i<n;i++)
{
fflush(stdin);
printf("\n Name of Book:- ");
gets(b.name);
printf("\n Number of Page:- ");
scanf("%d", &b.page);
fwrite(&b,sizeof(b),1,fp);
}
fclose(fp);
clrscr();
fp=fopen("Book.dat","rb");
printf("\n Name of Book \t Number of Page");
while(fread(&b,sizeof(b),1,fp)==1)
printf("\n %s \t %d",b.name,b.page);
fclose(fp);
getch();
}
Program 2:
#include<stdio.h>
#include<conio.h>
struct student
{
char name[40];
int roll;
int marks;
};
------------------------------------------------------------------------------------------------------------------------------------------------
10 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------
void main()
{
FILE *fp;
struct student s;
char ch;
fp=fopen("Student.dat","w");
if(fp==NULL)
{
printf("\n File can't be opened");
exit(0);
}
do
{
printf("\n Input Roll No.:- ");
scanf("%d",&s.roll);
fflush(stdin);
printf("\n Input Name:- ");
gets(s.name);
printf("\n Input Total Marks:- ");
scanf("%d",&s.marks);
fwrite(&s,sizeof(s),1,fp);
printf("\n Any more data (y/n):- ");
ch=getche();
}while(ch=='y'||ch=='Y');
printf("\n Data Written Successfully...");
fclose(fp);
getch();
}
------------------------------------------------------------------------------------------------------------------------------------------------
11 | Compiled By: Er. M.B. Singh Unit 9: File Handling
------------------------------------------------------------------------------------------------------------------------------------------------