File Handling in C
File handling allows programs to read from and write to files on disk. C provides comprehensive file I/O functions for data persistence.
"File handling in C is the process of creating, reading, writing, and manipulating files on the disk."
What is File Handling?
File handling refers to the process of performing input and output operations on files. Files provide a way to store data permanently on disk, allowing programs to save and retrieve information even after execution ends.
File Pointers
File pointers are special pointers of type FILE* that point to file structures containing file information.
FILE Structure
typedef struct {
// File control information
} FILE;
Opening Files - fopen()
The fopen() function opens a file and returns a file pointer.
fopen() Syntax and Modes
FILE *fopen(const char *filename, const char *mode);
| Mode | Description |
|---|---|
| "r" | Open for reading (file must exist) |
| "w" | Open for writing (creates new file or truncates existing) |
| "a" | Open for appending (creates new file if doesn't exist) |
| "r+" | Open for reading and writing |
| "w+" | Open for reading and writing (creates new or truncates) |
| "a+" | Open for reading and appending |
| "rb", "wb", "ab" | Binary modes for reading, writing, appending |
Basic File Opening
#include <stdio.h>
int main() {
FILE *file_ptr;
// Open file for writing
file_ptr = fopen("example.txt", "w");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("File opened successfully!\n");
// Close the file
fclose(file_ptr);
return 0;
}
Closing Files - fclose()
The fclose() function closes an opened file and frees the file pointer.
fclose() Syntax
int fclose(FILE *stream);
Proper File Handling
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("data.txt", "w");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Perform file operations here
fprintf(file_ptr, "Hello, World!\n");
// Always close the file
if (fclose(file_ptr) == 0) {
printf("File closed successfully!\n");
} else {
printf("Error closing file!\n");
}
return 0;
}
Writing to Files
fprintf() - Formatted Writing
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("student.txt", "w");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write formatted data
fprintf(file_ptr, "Name: %s\n", "John Doe");
fprintf(file_ptr, "Age: %d\n", 20);
fprintf(file_ptr, "GPA: %.2f\n", 3.75);
fclose(file_ptr);
printf("Data written to file successfully!\n");
return 0;
}
fputc() - Character Writing
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("characters.txt", "w");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write characters one by one
char text[] = "Hello, World!";
for (int i = 0; text[i] != '\0'; i++) {
fputc(text[i], file_ptr);
}
fclose(file_ptr);
printf("Characters written to file!\n");
return 0;
}
fputs() - String Writing
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("message.txt", "w");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write strings
fputs("Welcome to AIVista India!\n", file_ptr);
fputs("Learn C Programming\n", file_ptr);
fputs("File Handling Tutorial\n", file_ptr);
fclose(file_ptr);
printf("Strings written to file!\n");
return 0;
}
Reading from Files
fscanf() - Formatted Reading
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("student.txt", "r");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
char name[50];
int age;
float gpa;
// Read formatted data
fscanf(file_ptr, "Name: %s\n", name);
fscanf(file_ptr, "Age: %d\n", &age);
fscanf(file_ptr, "GPA: %f\n", &gpa);
printf("Read from file:\n");
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("GPA: %.2f\n", gpa);
fclose(file_ptr);
return 0;
}
fgetc() - Character Reading
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("characters.txt", "r");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
char ch;
printf("File contents: ");
// Read characters one by one
while ((ch = fgetc(file_ptr)) != EOF) {
printf("%c", ch);
}
printf("\n");
fclose(file_ptr);
return 0;
}
fgets() - String Reading
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("message.txt", "r");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
char line[100];
printf("File contents:\n");
// Read lines
while (fgets(line, sizeof(line), file_ptr) != NULL) {
printf("%s", line);
}
fclose(file_ptr);
return 0;
}
Binary File Operations
fwrite() - Binary Writing
#include <stdio.h>
struct Student {
int roll_number;
char name[50];
float marks;
};
int main() {
FILE *file_ptr = fopen("students.dat", "wb");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
struct Student students[3] = {
{101, "Alice", 85.5},
{102, "Bob", 92.0},
{103, "Charlie", 78.5}
};
// Write array of structures
fwrite(students, sizeof(struct Student), 3, file_ptr);
fclose(file_ptr);
printf("Binary data written successfully!\n");
return 0;
}
fread() - Binary Reading
#include <stdio.h>
struct Student {
int roll_number;
char name[50];
float marks;
};
int main() {
FILE *file_ptr = fopen("students.dat", "rb");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
struct Student students[3];
// Read array of structures
fread(students, sizeof(struct Student), 3, file_ptr);
printf("Student Records:\n");
for (int i = 0; i < 3; i++) {
printf("Roll: %d, Name: %s, Marks: %.2f\n",
students[i].roll_number,
students[i].name,
students[i].marks);
}
fclose(file_ptr);
return 0;
}
File Positioning
fseek() - File Positioning
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("data.txt", "w+");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
// Write some data
fprintf(file_ptr, "Hello World!");
// Move to beginning
fseek(file_ptr, 0, SEEK_SET);
// Read from beginning
char buffer[20];
fgets(buffer, sizeof(buffer), file_ptr);
printf("Read: %s\n", buffer);
// Move to position 6 (after "Hello ")
fseek(file_ptr, 6, SEEK_SET);
fprintf(file_ptr, "C Programming");
// Move to beginning and read entire file
fseek(file_ptr, 0, SEEK_SET);
fgets(buffer, sizeof(buffer), file_ptr);
printf("Modified: %s\n", buffer);
fclose(file_ptr);
return 0;
}
ftell() - Current Position
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("position.txt", "w+");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return 1;
}
fprintf(file_ptr, "AIVista India");
printf("Current position: %ld\n", ftell(file_ptr));
fseek(file_ptr, 0, SEEK_SET);
printf("After seeking to start: %ld\n", ftell(file_ptr));
fseek(file_ptr, 0, SEEK_END);
printf("At end of file: %ld\n", ftell(file_ptr));
fclose(file_ptr);
return 0;
}
Error Handling and File Status
feof() and ferror()
#include <stdio.h>
int main() {
FILE *file_ptr = fopen("nonexistent.txt", "r");
if (file_ptr == NULL) {
printf("File does not exist!\n");
return 1;
}
char ch;
while ((ch = fgetc(file_ptr)) != EOF) {
printf("%c", ch);
}
if (feof(file_ptr)) {
printf("\nEnd of file reached.\n");
}
if (ferror(file_ptr)) {
printf("Error reading file.\n");
}
fclose(file_ptr);
return 0;
}
Practical Examples
1. Student Record Management System
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
int roll_number;
char name[50];
float marks;
};
void addStudent() {
FILE *file_ptr = fopen("students.txt", "a");
if (file_ptr == NULL) {
printf("Error opening file!\n");
return;
}
struct Student s;
printf("Enter roll number: ");
scanf("%d", &s.roll_number);
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter marks: ");
scanf("%f", &s.marks);
fprintf(file_ptr, "%d %s %.2f\n", s.roll_number, s.name, s.marks);
fclose(file_ptr);
printf("Student added successfully!\n");
}
void displayStudents() {
FILE *file_ptr = fopen("students.txt", "r");
if (file_ptr == NULL) {
printf("No student records found!\n");
return;
}
struct Student s;
printf("\nStudent Records:\n");
printf("Roll\tName\t\tMarks\n");
printf("----\t----\t\t-----\n");
while (fscanf(file_ptr, "%d %s %f", &s.roll_number, s.name, &s.marks) != EOF) {
printf("%d\t%s\t\t%.2f\n", s.roll_number, s.name, s.marks);
}
fclose(file_ptr);
}
int main() {
int choice;
while (1) {
printf("\nStudent Management System\n");
printf("1. Add Student\n");
printf("2. Display Students\n");
printf("3. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addStudent();
break;
case 2:
displayStudents();
break;
case 3:
exit(0);
default:
printf("Invalid choice!\n");
}
}
return 0;
}
2. File Copy Program
#include <stdio.h>
int main() {
FILE *source_file, *dest_file;
char source_name[50], dest_name[50];
char ch;
printf("Enter source file name: ");
scanf("%s", source_name);
printf("Enter destination file name: ");
scanf("%s", dest_name);
source_file = fopen(source_name, "r");
if (source_file == NULL) {
printf("Cannot open source file!\n");
return 1;
}
dest_file = fopen(dest_name, "w");
if (dest_file == NULL) {
printf("Cannot create destination file!\n");
fclose(source_file);
return 1;
}
// Copy file character by character
while ((ch = fgetc(source_file)) != EOF) {
fputc(ch, dest_file);
}
printf("File copied successfully!\n");
fclose(source_file);
fclose(dest_file);
return 0;
}
File Handling Best Practices
- Always check if fopen() returns NULL
- Always close files after use with fclose()
- Use appropriate file modes (text vs binary)
- Handle errors gracefully
- Use full file paths when necessary
- Check for end-of-file with feof()
- Validate file operations
Common File Handling Errors
- Forgetting to close files (resource leaks)
- Not checking for file existence before operations
- Using wrong file modes
- Buffer overflow when reading strings
- Not handling file I/O errors
- Attempting to read beyond end of file
Text Files vs Binary Files
| Aspect | Text Files | Binary Files |
|---|---|---|
| Storage | Human-readable characters | Raw binary data |
| Functions | fprintf, fscanf, fgets, fputs | fread, fwrite |
| Speed | Slower (format conversion) | Faster (direct I/O) |
| Size | May be larger | Compact |
| Use Case | Configuration files, logs | Images, executables, databases |
Conclusion
File handling is essential for data persistence in C programs. Understanding file operations allows you to create robust applications that can save and retrieve data. Practice with different file operations and error handling to master file I/O in C! 🚀