File handling in C allows programs to read from and write to files on disk. Files are
an essential part of most applications, as they enable data to persist beyond the
execution of a program. In C, the stdio.h library provides functions to perform file
operations like opening, reading, writing, and closing files.
1. Types of Files in C
In C, files can be categorized into two main types:
Text files: These contain plain text data, where each character is stored as a
sequence of bytes.
Binary files: These contain data in a format that is not human-readable,
such as images or executable files, and the data is stored as raw binary.
2. File Operations in C
C provides several functions for performing file operations. These include:
Opening a file
Reading from a file
Writing to a file
Closing a file
3. Opening a File
The fopen() function is used to open a file in C. It takes two arguments: the name
of the file and the mode in which the file should be opened. If the file is
successfully opened, fopen() returns a pointer to the file; otherwise, it returns
NULL.
, File Opening Modes:
"r": Open a file for reading.
"w": Open a file for writing (if the file exists, it is truncated).
"a": Open a file for appending (writing at the end of the file).
"r+": Open a file for reading and writing.
"w+": Open a file for reading and writing (if the file exists, it is truncated).
"a+": Open a file for reading and appending.
Example of opening a file:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
// Perform file operations
fclose(file); // Close the file
return 0;
}
4. Reading from a File
You can read data from a file using functions like fgetc(), fgets(), or fread().
fgetc(): Reads a single character from a file.
fgets(): Reads a line of text from a file.
fread(): Reads binary data from a file.