File handling in C allows you to create, read, write, and manipulate files on the disk. C provides a set of standard library functions to manage files, making it easy to perform file operations. Understanding file handling is essential for programs that need to store data permanently or process large amounts of data efficiently.
Types of Files in C
Text Files: These files store data in human-readable format. Each line of the file is terminated by a newline character.
Binary Files: These files store data in binary format, which is not human-readable. They can contain any type of data, including images and executable files.
File Handling Functions in C
C provides several standard library functions for file handling, primarily defined in the <stdio.h>
header file.
1. Opening a File
To work with a file, you first need to open it using the fopen
function:
FILE *fopen(const char *filename, const char *mode);
filename
: The name of the file to open.mode
: The mode in which the file is to be opened (e.g., read, write, append).
Common File Modes:
"r"
: Read mode. Opens a file for reading. The file must exist."w"
: Write mode. Creates a new file or truncates an existing file for writing."a"
: Append mode. Opens a file for writing at the end of the file without truncating it."r+"
: Read and write mode. Opens a file for both reading and writing. The file must exist."w+"
: Read and write mode. Creates a new file or truncates an existing file for reading and writing."a+"
: Read and append mode. Opens a file for reading and appending. The file is created if it does not exist.
Example: Opening a File
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r"); // Open a file in read mode
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
// File operations go here
fclose(file); // Close the file
return 0;
}
2. Closing a File
Always close a file after finishing operations on it using the fclose
function:
int fclose(FILE *stream);
This function takes a file pointer as an argument and closes the associated file.
3. Reading from a File
You can read data from a file using various functions:
fgetc(FILE *stream)
: Reads a single character from the file.fgets(char *str, int n, FILE *stream)
: Reads a line from the file.fscanf(FILE *stream, const char *format, ...)
: Reads formatted data from the file.
Example: Reading from a File
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), file)) {
printf("%s", line); // Print each line
}
fclose(file);
return 0;
}
4. Writing to a File
You can write data to a file using:
fputc(int char, FILE *stream)
: Writes a single character to the file.fputs(const char *str, FILE *stream)
: Writes a string to the file.fprintf(FILE *stream, const char *format, ...)
: Writes formatted data to the file.
Example: Writing to a File
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(file, "Hello, World!\n"); // Write a formatted string
fputs("This is a test.\n", file); // Write a string
fclose(file);
return 0;
}
5. File Positioning
You can manipulate the current position in a file using:
fseek(FILE *stream, long offset, int whence)
: Moves the file position indicator to a specific location.ftell(FILE *stream)
: Returns the current file position.rewind(FILE *stream)
: Sets the file position to the beginning of the file.
Example: File Positioning
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file.\n");
return 1;
}
fseek(file, 0, SEEK_END); // Move to the end of the file
long size = ftell(file); // Get the size of the file
printf("File size: %ld bytes\n", size);
rewind(file); // Move back to the beginning of the file
fclose(file);
return 0;
}
Error Handling
Always check if file operations succeed by checking if the file pointer is NULL
after opening a file and checking the return value of reading or writing functions.