File Handling in C
File handling in C allows you to store data permanently on disk and read or write it when needed. Unlike variables stored in memory, files preserve information even after the program ends.
This tutorial covers file handling basics, working with text and binary files, and provides practical examples.
Basics of File Handling
C provides a set of standard library functions to handle files. Files are represented using the `FILE` pointer type defined in `
Common file operations include:
- Opening a file (`fopen`)
- Closing a file (`fclose`)
- Reading from a file (`fgetc`, `fgets`, `fread`)
- Writing to a file (`fputc`, `fputs`, `fwrite`)
- Checking for errors (`feof`, `ferror`)
Opening and Closing Files
The `fopen` function is used to open a file. It requires the file name and mode (`r`, `w`, `a`, etc.).
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("example.txt", "w"); // Open file for writing
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
printf("File opened successfully.\n");
fclose(fp); // Close the file
return 0;
}
Modes for `fopen` include: `r` - read, `w` - write (overwrite), `a` - append, `r+` - read/write, `w+` - write/read (overwrite), `a+` - append/read.
Writing to a File
You can write text to a file using `fprintf` or `fputs`.
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(fp, "Hello, this is a sample file.\n");
fputs("Second line of text.\n", fp);
fclose(fp);
printf("Data written successfully.\n");
return 0;
}
Reading from a File
You can read text from a file using `fgetc` or `fgets`.
#include <stdio.h>
int main() {
char line[100];
FILE *fp = fopen("example.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
while (fgets(line, sizeof(line), fp)) {
printf("%s", line);
}
fclose(fp);
return 0;
}
Working with Binary Files
Binary files store data in raw format. You can read and write using `fread` and `fwrite`.
#include <stdio.h>
typedef struct {
int id;
char name[20];
} Student;
int main() {
Student s = {101, "Alice"};
FILE *fp = fopen("student.dat", "wb");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
fwrite(&s, sizeof(Student), 1, fp);
fclose(fp);
printf("Binary data written successfully.\n");
return 0;
}
Error Handling and File Checks
Always check if the file opened successfully and handle errors using `NULL` checks and `ferror`.
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
perror("Failed to open file");
return 1;
}
Conclusion
File handling in C is an essential skill for creating applications that need to store and retrieve data permanently.
By using functions like `fopen`, `fclose`, `fprintf`, `fgets`, `fread`, and `fwrite`, you can manage both text and binary files effectively.
Understanding file handling enables you to create real-world C programs like databases, file editors, and data processing tools.
Codecrown