C File Handling
In C, file handling allows you to create, open, read, write, and close files. C provides a set of functions to interact with files, making it easier to manage data stored in files. File handling is essential for programs that need to store large amounts of data or work with data that persists between program executions.
Opening a File
To perform any file operations, a file must first be opened using the fopen()
function. This function takes two arguments: the file name and the mode in which the file is opened.
FILE *fopen(const char *filename, const char *mode);
The mode
argument can be one of the following:
"r"
: Open for reading (file must exist)."w"
: Open for writing (creates an empty file if it doesn't exist)."a"
: Open for appending (creates a new file if it doesn't exist)."r+"
: Open for reading and writing."w+"
: Open for reading and writing (creates an empty file)."a+"
: Open for reading and appending.
Example: Opening and Writing to a File
#include <stdio.h>
int main()
{
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
fprintf(file, "Hello, File Handling in C!\n");
fclose(file);
return 0;
}
Output:
example.txt
.)
Reading from a File
After opening a file, data can be read using functions like fscanf()
or fgets()
. Here’s an example of reading from a file:
#include <stdio.h>
int main()
{
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Unable to open file.\n");
return 1;
}
char buffer[255];
fgets(buffer, sizeof(buffer), file);
printf("File content: %s", buffer);
fclose(file);
return 0;
}
Output:
Closing a File
Once the file operation is completed, the file should be closed using the fclose()
function to free system resources.
int fclose(FILE *file);
Error Handling
C provides functions like feof()
to check for end-of-file and ferror()
to check for errors during file operations.
#include <stdio.h>
int main()
{
FILE *file = fopen("non_existent_file.txt", "r");
if (file == NULL) {
printf("Error opening file: %s\n", strerror(errno));
}
return 0;
}
Output:
Key Functions
fopen()
: Opens a file with a specified mode.fclose()
: Closes a file.fscanf()
: Reads formatted input from a file.fprintf()
: Writes formatted output to a file.fgets()
: Reads a line from a file.fputs()
: Writes a string to a file.feof()
: Checks if the end of a file is reached.ferror()
: Checks for errors in a file operation.
Key Points
- Files are opened using the
fopen()
function with a specific mode. - Data can be written to a file using
fprintf()
orfputs()
. - Data can be read from a file using
fscanf()
,fgets()
, orfgetc()
. - Always close a file after finishing operations using
fclose()
. - Error handling and end-of-file checks are essential when working with files.