File Handling in C
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
When dealing with files, there are two types of files you should know about:
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 it 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.
We frequently use files for storing information which can be processed by our programs. In order to
store information permanently and retrieve it we need to use files.
Files are not only used for data. Our programs are also stored in files.
The editor which you use to enter your program and save it, simply manipulates files for you.
The commands cat, cpp, cmp are all programs which process your files.
In order to use files we have to learn about File I/O i.e. how to write information to a file and how to
read information from a file.
File Operations
In C, you can perform four major operations on files, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
As you know, you can have many files on your disk. If you wish to use a file in your programs, then
you must specify which file or files you wish to use.
Specifying the file you wish to use is referred to as opening the file.
When you open a file you must also specify what you wish to do with it i.e. Read from the file, Write
to the file, or both.
Because you may use a number of different files in your program, you must specify when reading or
writing which file you wish to use. This is accomplished by using a variable called a file pointer.
Every file you open has its own file pointer variable. When you wish to write to a file you specify the
file by using its file pointer variable.
You declare these file pointer variables as follows:
FILE *fopen(), *fp1, *fp2, *fp3;
The variables fp1, fp2, fp3 are file pointers. You may use any name you wish.
The file <stdio.h> contains declarations for the Standard I/O library and should always be included at
the very beginning of C programs using files.
Constants such as FILE, EOF and NULL are defined in <stdio.h>.
You should note that a file pointer is simply a variable like an integer or character.
It does not point to a file or the data in a file. It is simply used to indicate which file your I/O operation
refers to.
The function fopen is one of the Standard Library functions and returns a file pointer which you use to
refer to the file you have opened e.g.
fp = fopen( “prog.c”, “r”) ;
The above statement opens a file called prog.c for reading and associates the file pointer fp with the
file.
When we wish to access this file for I/O, we use the file pointer variable fp to refer to it.
You can have up to about 20 files open in your program - you need one file pointer for each file you
intend to use.
File I/O
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar()
and putc(c,fp) is similar to putchar(c).
Thus the statement
c = getc(fp);
reads the next character from the file referenced by fp and the statement
putc(c,fp);
writes the character c into file referenced by fp.
/* file.c: Display contents of a file on screen */
#include <stdio.h>
void main()
{
FILE *fopen(), *fp;
int c ;
fp = fopen( “prog.c”, “r” );
c = getc( fp ) ;
while ( c != EOF )
{
putchar( c );
c = getc ( fp );
}
fclose( fp );
}
In this program, we open the file prog.c for reading.
We then read a character from the file. This file must exist for this program to work.
If the file is empty, we are at the end, so getc returns EOF a special value to indicate that the end of
file has been reached. (Normally -1 is used for EOF)
The while loop simply keeps reading characters from the file and displaying them, until the end of the
file is reached.
The function fclose is used to close the file i.e. indicate that we are finished processing this file.
We could reuse the file pointer fp by opening another file.
This program is in effect a special purpose cat command. It displays file contents on the screen, but
only for a file called prog.c.
By allowing the user enter a file name, which would be stored in a string, we can modify the above to
make it an interactive cat command:
The function exit() is a special function which terminates your program immediately.
exit(0) mean that you wish to indicate that your program terminated successfully whereas a nonzero
value means that your program is terminating due to an error condition.
Alternatively, you could prompt the user to enter the filename again, and try to open it again:
fp = fopen (fname, “r”) ;
while ( fp == NULL)
{
printf(“Cannot open %s for reading \n”, fname );
printf(“\n\nEnter filename :” );
gets( fname );
fp = fopen (fname, “r”) ;
}
In this code fragment, we keep reading filenames from the user until a valid existing filename is
entered.
Through file handling, one can perform operations like create, modify, delete etc on system files.
Here in this article I try to bring in the very basic of file handling. Hope this article will clear the
top layer of this multilayer aspect.
File handling functions
In this article, we will cover the following functions that are popularly used in file handling :
fopen()
FILE *fopen(const char *path, const char *mode);
The fopen() function is used to open a file and associates an I/O stream with it. This function
takes two arguments. The first argument is a pointer to a string containing name of the file to be
opened while the second argument is the mode in which the file is to be opened. The mode can
be :
‘r’ : Open text file for reading. The stream is positioned at the beginning of the file.
‘r+’ : Open for reading and writing. The stream is positioned at the beginning of the file.
‘w’ : Truncate file to zero length or create text file for writing. The stream is positioned at
the beginning of the file.
‘w+’ : Open for reading and writing. The file is created if it does not exist, otherwise it is
truncated. The stream is positioned at the beginning of the file.
‘a’ : Open for appending (writing at end of file). The file is created if it does not exist. The
stream is positioned at the end of the file.
‘a+’ : Open for reading and appending (writing at end of file). The file is created if it does
not exist. The initial file position for reading is at the beginning of the file, but output is
always appended to the end of the file.
The fopen() function returns a FILE stream pointer on success while it returns NULL in case of a
failure.
summary
Opening Modes in Standard I/O
Mode Meaning of Mode During Inexistence of file
If the file does not exist,
r Open for reading.
fopen() returns NULL.
If the file does not exist,
rb Open for reading in binary mode.
fopen() returns NULL.
If the file exists, its contents
are overwritten.
w Open for writing.
If the file does not exist, it will
be created.
If the file exists, its contents
are overwritten.
wb Open for writing in binary mode.
If the file does not exist, it will
be created.
Open for append.
If the file does not exist, it will
a Data is added to the end of the
be created.
file.
Open for append in binary mode.
If the file does not exist, it will
ab Data is added to the end of the
be created.
file.
Open for both reading and If the file does not exist,
r+
writing. fopen() returns NULL.
Opening Modes in Standard I/O
Mode Meaning of Mode During Inexistence of file
Open for both reading and If the file does not exist,
rb+
writing in binary mode. fopen() returns NULL.
If the file exists, its contents
Open for both reading and are overwritten.
w+
writing. If the file does not exist, it will
be created.
If the file exists, its contents
Open for both reading and are overwritten.
wb+
writing in binary mode. If the file does not exist, it will
be created.
Open for both reading and If the file does not exist, it will
a+
appending. be created.
Open for both reading and If the file does not exist, it will
ab+
appending in binary mode. be created.
fread() and fwrite()
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
The functions fread/fwrite are used for reading/writing data from/to the file opened by fopen
function. These functions accept three arguments. The first argument is a pointer to buffer used
for reading/writing the data. The data read/written is in the form of ‘nmemb’ elements each ‘size’
bytes long.
In case of success, fread/fwrite return the number of bytes actually read/written from/to the
stream opened by fopen function. In case of failure, a lesser number of byes (then requested to
read/write) is returned.
INBUILT FUNCTIONS FOR FILE HANDLING IN C LANGUAGE:
C programming language offers many inbuilt functions for handling files. They are given below.
Please click on each function name below to know more details, example programs, output for
the respective file handling function.
File
handling functions Description
fopen () fopen () function creates a new file or opens an existing file.
fclose () fclose () function closes an opened file.
getw () getw () function reads an integer from file.
putw () putw () functions writes an integer to file.
fgetc () fgetc () function reads a character from file.
fputc () fputc () functions write a character to file.
gets () gets () function reads line from keyboard.
puts () puts () function writes line to o/p screen.
fgets () fgets () function reads string from a file, one line at a time.
fputs () fputs () function writes string to a file.
feof () feof () function finds end of file.
fgetchar () fgetchar () function reads a character from keyboard.
fprintf () fprintf () function writes formatted data to a file.
fscanf () fscanf () function reads formatted data from a file.
fputchar () function writes a character onto the output screen from
fputchar () keyboard input.
fseek () fseek () function moves file pointer position to given location.
SEEK_SET SEEK_SET moves file pointer position to the beginning of the file.
SEEK_CUR SEEK_CUR moves file pointer position to given location.
SEEK_END SEEK_END moves file pointer position to the end of file.
ftell () ftell () function gives current position of file pointer.
rewind () function moves file pointer position to the beginning of the
rewind () file.
getc () getc () function reads character from file.
getch () getch () function reads character from keyboard.
getche () function reads character from keyboard and echoes to o/p
getche () screen.
getchar () getchar () function reads character from keyboard.
putc () putc () function writes a character to file.
putchar () putchar () function writes a character to screen.
printf () printf () function writes formatted data to screen.
sprinf () sprinf () function writes formatted output to string.
scanf () scanf () function reads formatted data from keyboard.
sscanf () sscanf () function Reads formatted input from a string.
remove () remove () function deletes a file.
fflush () fflush () function flushes a file.