UNIT-9
FILE HANDLING
File handling in C is the process in which we create, open, read, write, and close
operations on a file. C language provides different functions such as fopen(), fwrite(),
fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file
operations in our program.
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
Why do we need File Handling in C?
So far the operations using the C program are done on a prompt/terminal which is not
stored anywhere. The output is deleted when the program is closed. But in the software
industry, most programs are written to store the information fetched from the program.
The use of file handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few features of
using files:
Reusability: The data stored in the file can be accessed, updated, and deleted
anywhere and anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another in the
computer system. The risk of flawed coding is minimized with this feature.
Efficient: A large amount of input may be required for some programs. File
handling allows you to easily access a part of a file using few instructions which
saves a lot of time and reduces the chance of errors.
Storage Capacity: Files allow you to store a large amount of data without having
to worry about storing everything simultaneously in a program.
Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are
as follows:
1. Text file − A text file contains data in the form of ASCII characters and is generally
used to store a stream of characters. Each line in a text file ends with a new line character
("\n"), and generally has a ".txt" extension.
2. Binary file − A binary file contains data in raw bits (0 and 1). Different application
programs have different ways to represent bits and bytes and use different file formats.
The image files (.png, .jpg), the executable files (.exe, .com), etc. are the examples of
binary files.
Working with files: When working with files, you need to declare a pointer of type
file. This declaration is needed for communication between the file and the program.
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file. A
list of file functions are given below:
No. Function Description
1 fopen() opens new or existing file
2 fprintf() write data into the file
3 fscanf() reads data from the file
4 fputc() writes a character into the file
5 fgetc() reads a character from file
6 fclose() closes the file
7 fseek() sets the file pointer to given position
8 fputw() writes an integer to file
9 fgetw() reads an integer from file
10 ftell() returns current position
11 rewind() sets the file pointer to the beginning of the file
Common File Modes: We can use one of the following modes in the
fopen() function.
Mode Description
r opens a text file in read mode
w opens a text file in write mode
a opens a text file in append mode
r+ opens a text file in read and write mode
w+ opens a text file in read and write mode
a+ opens a text file in read and write mode
rb opens a binary file in read mode
wb opens a binary file in write mode
ab opens a binary file in append mode
rb+ opens a binary file in read and write mode
wb+ opens a binary file in read and write mode
ab+ opens a binary file in read and write mode
Opening a file - for creation and edit
Opening a file is performed using the fopen() function defined in the stdio.h header file.
Closing a File: The file (both text and binary) should be closed after reading/writing.
Closing a file is performed using the fclose() function.
Example of Opening a File
// C Program to illustrate file opening
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;
// opening the file in read mode
fptr = fopen("filename.txt", "r");
// checking if the file is opened successfully
if (fptr == NULL) {
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}
return 0;
}
Output
The file is not opened. The program will now exit.
The file is not opened because it does not exist in the source directory. But the fopen()
function is also capable of creating a file if it does not exist. It is shown below
Create a File in C:
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found
such as w, w+, wb, wb+, a, a+, ab, and ab+.
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
}
Output
The file is created Successfully.
Reading and writing to a text file: For reading and writing to a text file, we use
the functions fprintf() and fscanf(). They are just the file versions of printf() and
scanf(). The only difference is that fprintf() and fscanf() expects a pointer to the
structure FILE.
Example 1: Write to a text file
This program takes a number from the user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C
drive of your computer. When you open the file, you can see the integer you entered.
Example 2: Read from a text file
This program reads the integer present in the program.txt file and prints it onto the
screen.
If you successfully created the file from Example 1, running this program will get you
the integer you entered.
Other functions like fgetchar(), fputc() etc. can be used in a similar way.