Background
The program that we have executed so far accepts data from the keyboard and gives output to visual display
unit. This type of I/O is called console I/O. The console input/output work fine as long as the data is small.
It becomes very inconvenient and time consuming to handle the large volume of data through console I/O. And
the data get lost or destroy when the program is terminated or the computer system is turn off.
To overcome these problems, here comes the need of file handling in C.
File handling in C enables us to create, write, read and update the files stored on the local file system
through our C program. The basic steps for using a File in C are always the same.
- 1. Create a variable of type
"FILE*"
- 2. Open the file using the
"fopen()" function ans assign the "file" to the variable.
- 3. Check to make sure the file
was successfully opened by checking to see if the variable == NULL. If it does, an error has occured.
- 4. Use the Input/Output file
handeling function to write/read from the file. Usually these function calls are placed in a loop.
- 5. Closing the file.
1. Creating a variable of type
"FILE*"
While working with data file, we need buffer area (i.e, temporary memory) where information is stored for
short period of time in the course of transferring data between computer memory and data file. The buffer area
is established by creating a variable of type "FILE*"
Here, FILE is a special structure (keyword), declared in header file stdio.h and *fp is file pointer variable
that stores the beginning address of the buffer area allocated after a file has been opened.
Also file pointer contains other information about the file including file_name, new position of the file,
whether the file is being read or written, and whether errors or end-of-file have occured. Basically file
pointer acts as a communication link between the program and the file.
2. Opening the file using fopen()
Before performing an input/output function in file, a file must be opened. The fopen() function is used to
open a file defined in the stdio.h header file. The syntax of the fopen() is given below:
The function fopen() returns a pointer to the beginning of the buffer area associated with the file (i.e. the
first address of the allocated buffer area is stored in pointer variable *pt).
The fopen() function accepts two arguments.
- The first is the name of the file. If the file is stored at some specific location, then we must mention
the path at which the file is stored. For example, a file can be like “D:\\Student.txt”.
- And second is the mode in which file is to be opened. It is also string.
We can use one of the following modes in the fopen() function.
Mode |
Binary Mode |
Meaning of Mode |
During Existence of file |
Pointer Position |
During Inexistence of file |
w |
wb |
Opens new file for writing mode. |
If the file exists, its contents are destroyed. |
At the beginning of the file |
If the file does not exit, it will be created. |
r |
rb |
Opens file for reading mode. |
If the file exists, its contents are not destroyed. |
At the beginning of the file |
If the file does not exist, fopen() returns NULL. |
a |
ab |
Opens file for appending mode. |
If the file exists, its contents are not destroyed. |
At the end of the file. |
If the file does not exist, it will be created. |
w+ |
w+b or wb+ |
Opens file for both writing and reading. |
If the file exists, its contents are destroyed. |
At the beginning of the file |
If the file does not exist, it will be created. |
r+ |
r+b or rb+ |
Opens file for both writing and reading purpose. |
If the file exists, its contents are not destroyed. |
At the beginning of the file. |
If the file does not exist, fopen() returns NULL. |
a+ |
a+b or ab+ |
Opens file for both reading and appending purpose. |
If the file exists, its contents are not destroyed. |
The initial file position for reading is at the beginning of the file, but
output is always appended to the end of the file. |
If the file does not exist, new file will be created. |
Note:
The distinguishing feature of a file is its end-of-file mark.
We refer to this mark as EOF. EOF typically has the value -1.
3. Error Handling in File
Operations (Updated)
File handling operations may fail due to anyone of the following reasons:
- A file for reading may not be present on the disk.
- Insufficient disk space for opening a file for writing.
- Write protected disk does not allow storage of data on it.
- Dealing with corrupt file.
To handle these error we need to check whether the intended data files has opened successfully or not by
comparing the result of fopen() function with NULL character.
Since fopen() function points to the beginning of the file if file is opened successfully otherwise it returns
NULL.
Code for handling error during file opening.
Other useful functions for hanlding error during read/write operations are:
ferror() |
This function reports any error during a read/write operation on a file. |
Its prototype is: int ferror(file_pointer_variable); |
perror() |
This function writes the error message specified by the compiler. |
Its prototype is: void perror(error_message); |
Note: Exit is a jump statement in C which takes an integer (zero or non-zero) to represent different exit
status.
Exit Success is indicated by exit(0) statement which means successful termination of the program.
Exit Failure is indicated by exit(1) which means the abnormal termination of the program.
We can use different integer other than 1 to indicate different types of errors.
4. File Handling Input/Output
function
There are many I/O functions in the C library which are given below.
|
Function |
Description |
Example |
Character I/O function |
fputc |
Used to write a character to a file. |
fputc(ch,fp) |
fgetc |
Used to read a character from a file. |
ch = fgetc(fp) |
String Input/Output function |
fputs |
Used to write a string to a file. |
fputs(ch,fp) |
fgets |
Used to read a string from file. |
fgets(ch,50,fp) |
Formatted Input/Output function |
fprintf() |
Used to write integer, float, char or string data to a file. |
fprintf(fp, "%s%d%f", s.name, s.rollno, s.marks) |
fscanf() |
Used to read integer, float, char or string value from a file. |
fscanf(fp, "%s%d%d", &s.name, &s.age, &s.marks) |
Record Input/Output function |
fwrite() |
Used for record output |
fwrite(&s, sizeof(s) ,1 ,fp) |
fread() |
Used for record input. |
fread(&s, sizeof(s) ,1 ,fp) |
5. fclose() function
The fclose() function is used to close a file. The file must be closed after performing all the operations on
it.
Closing a file ensures that all outstanding information associated with the file is flushed out from the
buffers and all links to the file are broken. It also prevents any accidental misuse of the file.
The syntax of fclose() function is given below.
Note: If the file is open for writing or appending, fclose() writes any data remaining in the file's buffer
to the file and appends the end of file (EOF) mark after the last character written.
If the file is open for reading, fclose() ignores any data left in the file's buffer and closes the
connection.
fclose() returns 0 if successful, EOF if unsuccessful. fclose() fails if the storage device is full, an I/O
error occurs or the storage medium is prematurely removed.