File Handling in C
File handling is important in C because it allows you to read and write data to files on a disk, rather than just in memory. This makes it possible to save data to be used later, or to read data from a file created by another program.
For example, imagine you are creating a program that records the high scores for a video game. Without file handling, the high scores would be lost every time the program is closed. By using file handling, the program can save the high scores to a file on the user's computer, so that they can be loaded the next time the program is run.
File handling also enables you to read data from files created by other programs. For example, you could use file handling to read data from a spreadsheet created in Microsoft Excel, or to read an image file and display it on the screen. The possibilities are endless, and file handling is a very important tool for creating powerful and flexible programs in C.
Operations on Files
-
Opening a file: You can open a file using the
fopen()
function, which takes two arguments: the name of the file, and the mode in which you want to open the file (e.g., "r" for reading, "w" for writing, "a" for appending, etc.). -
Creating a file: You can create a new file if file is not there by using the
fopen()
function. -
Reading from a file: Once a file is open, you can use various functions to read data from the file, such as
fgetc()
to read a single character,fgets()
to read a line of text, andfread()
to read a block of data. -
Writing to a file: You can also use functions like
fprintf()
andfwrite()
to write data to an open file. -
Moving the file pointer: The file pointer is a pointer that keeps track of the current position in the file. You can use functions like
fseek()
andrewind()
to move the file pointer to a different position in the file. -
Closing a file: Once you are done working with a file, it is important to close it using the
fclose()
function. This ensures that any changes you made to the file are saved and any resources used by the file are freed. -
Error handling: It's important to check for errors when working with files, such as when trying to open a file that does not exist or when trying to read from a file that has reached the end of its data. You can use the
ferror()
andfeof()
functions to check for errors and end-of-file conditions.
Two Main Types of Files: Text files and Binary files
-
Text files: These files contain plain text and can be opened and edited using a text editor. Text files are stored with the ".txt" file extension and each line of text is separated by a newline character. In C, the
fprintf()
andfscanf()
functions are used to write and read text files respectively. -
Binary files: These files contain binary data and can't be opened and edited using a text editor. Binary files are stored with the ".bin" file extension and there is no delimiter between different data in the file. In C, the
fwrite()
andfread()
functions are used to write and read binary files respectively.
Text files are human-readable and easy to understand, while binary files are not human-readable and only can be read and written by a program. It depends on the use case, you can choose which type of file you want to use to store your data.
For example, a text file is suitable for storing a list of names and addresses, while a binary file is suitable for storing an image or a video.
It's important to note that when you are working with binary files, you need to be careful with the data types and the size of the data you are reading and writing. If the data type or size of the data in the file does not match the data type or size of the variable you are using to read or write the data, it can lead to unexpected results or even crashes.
Functions for File Handling in C
There are several built-in functions in C for file handling. Here is a list of some of the most commonly used functions, along with a brief explanation of their purpose:
-
fopen()
: This function is used to open a file. It takes two arguments: the name of the file and the mode in which to open the file. The mode can be "r" for reading, "w" for writing, "a" for appending, "r+" for reading and writing, and "w+" for reading and writing. -
fclose()
: This function is used to close a file. It takes a single argument: the file pointer returned by thefopen()
function. -
fprintf()
: This function is used to write data to a file. It takes two arguments: the file pointer returned by thefopen()
function and a format string, followed by any additional arguments required by the format string. -
fscanf()
: This function is used to read data from a file. It takes two arguments: the file pointer returned by thefopen()
function and a format string, followed by any additional arguments required by the format string. -
fread()
: This function is used to read binary data from a file. It takes four arguments: a pointer to the buffer where the data will be stored, the size of each element to be read, the number of elements to be read, and the file pointer returned by thefopen()
function. -
fwrite()
: This function is used to write binary data to a file. It takes four arguments: a pointer to the buffer containing the data, the size of each element to be written, the number of elements to be written, and the file pointer returned by thefopen()
function. -
rewind()
: This function is used to move the file pointer back to the beginning of the file. It takes a single argument: the file pointer returned by thefopen()
function. -
fseek()
: This function is used to move the file pointer to a specific position in the file. It takes three arguments: the file pointer returned by thefopen()
function, the number of bytes to move the pointer, and the position to move the pointer from (e.g.,SEEK_SET
for the beginning of the file,SEEK_CUR
for the current position,SEEK_END
for the end of the file). -
feof()
: This function is used to check if the end-of-file marker has been reached. It takes a single argument: the file pointer returned by thefopen()
function. -
remove()
: This function is used to delete a file. It takes a single argument: the name of the file to be deleted.
It's important to note that when you're done with a file, you must close it with fclose()
or else you may encounter errors with your files.
Modes of Operations
In file handling in C, there are several modes of operation that can be used when opening a file. These modes determine how the file can be accessed and what actions can be performed on it. The most common modes of operation are:
-
"r" (read mode): This mode is used to open an existing file for reading. If the file does not exist, the
fopen()
function returns aNULL
pointer. -
"w" (write mode): This mode is used to open a new file for writing. If the file already exists, its contents will be truncated and overwritten with new data. If the file does not exist, a new file will be created.
-
"a" (append mode): This mode is used to open an existing file for writing. If the file does not exist, a new file will be created. In this mode, the file pointer is positioned at the end of the file, so new data will be added to the end of the file.
-
"r+" (read and write mode): This mode is used to open an existing file for both reading and writing. The file pointer is positioned at the beginning of the file.
-
"w+" (write and read mode): This mode is used to open a new file for both reading and writing. If the file already exists, its contents will be truncated and overwritten with new data. If the file does not exist, a new file will be created.
It's important to choose the correct mode when opening a file. For example, if you try to write to a file opened in read mode, it will cause an error. And if you try to read from a file opened in write mode, you will not be able to read any data from it.
Opening and Closing of Files
The syntax for opening a file in C is as follows:
FILE *fopen(const char *filename, const char *mode);
filename
is a string that contains the name of the file to be opened.mode
is a string that specifies the mode in which the file will be opened. The most commonly used modes are "r" for reading, "w" for writing, and "a" for appending.
The fopen
function returns a pointer to the FILE
object that represents the opened file. If the file cannot be opened, the function returns a NULL
pointer.
FILE *file;
file = fopen("example.txt", "r"); // Open the file "example.txt" in read mode
if (file == NULL)
{
printf("Error opening file
");
return 1;
}
The syntax for closing a file in C is as follows:
int fclose(FILE *stream);
stream
is a pointer to theFILE
object that represents the file to be closed.
The fclose
function returns zero if the file is closed successfully, and EOF
if an error occurs.
FILE *file;
file = fopen("example.txt", "r"); // Open the file "example.txt" in read mode
if (file == NULL)
{
printf("Error opening file");
return 1;
}
// Read and process the contents of the file
if (fclose(file) != 0) // Close the file
{
printf("Error closing file");
return 1;
}
In the above example, first, we are opening the file example.txt in read mode using fopen
function and checking if the file is opened successfully or not. Next, we are closing the file using fclose
function and checking if the file is closed successfully or not.
For Example: Simple Program reading a File using getc() Function
#include <stdio.h>
int main()
{
// Declare variables
char ch;
FILE *file;
// Open a file for reading
file = fopen("example.txt", "r");
// Check if file is opened successfully
if (file == NULL)
{
printf("Error opening file");
return 1;
}
// Read the contents of the file using fgetc()
while ((ch = fgetc(file)) != EOF)
{
printf("%c", ch);
}
// Close the file
fclose(file);
return 0;
}
In the above program,
- First, we include the
stdio.h
header file, which contains the functions for file handling in C. - Next, we declare a character variable
ch
to hold the character read from the file and a pointer to aFILE
object, which we will use to work with the file. - Then we open the file example.txt in read mode using
fopen
function, - Next, we are checking whether the file is opened successfully or not.
- Next, we are reading the contents of the file using
fgetc
function and printing it usingprintf
function inside a while loop until EOF(end of file) is reached, - Finally, we are closing the file using
fclose
function.