1. Introduction to File Handling
File handling in C allows programs to store data permanently on storage devices and retrieve it when needed. Unlike variables that exist only during program execution, files provide persistent storage.
Key Concepts:
- Stream: A sequence of bytes flowing from source to destination
- File Pointer:
FILEstructure that contains information about the file - Modes: Different ways to open files (read, write, append, etc.)
// Required header for file operations
#include <stdio.h>
#include <stdio.h>
2. File Operations
| Operation | Function | Description |
|---|---|---|
| Open | fopen() |
Opens a file and returns a file pointer |
| Close | fclose() |
Closes an opened file |
| Read | fscanf(), fgets(), fread() |
Reads data from file |
| Write | fprintf(), fputs(), fwrite() |
Writes data to file |
| Position | fseek(), ftell(), rewind() |
Manages file position |
| Error Check | feof(), ferror() |
Checks for errors |
3. Opening a File
Syntax:
FILE *fopen(const char *filename, const char *mode);
File Modes:
| Mode | Description |
|---|---|
"r" |
Read mode (file must exist) |
"w" |
Write mode (creates or truncates) |
"a" |
Append mode (creates or appends) |
"r+" |
Read/write mode (file must exist) |
"w+" |
Read/write mode (creates or truncates) |
"a+" |
Read/append mode (creates or appends) |
"rb", "wb", "ab" |
Binary file modes |
Example:
#include <stdio.h>
int main() {
FILE *file;
// Open file for writing
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("File opened successfully!\n");
fclose(file);
return 0;
}
int main() {
FILE *file;
// Open file for writing
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
printf("File opened successfully!\n");
fclose(file);
return 0;
}
4. Closing a File
Syntax:
int fclose(FILE *stream);
Example:
FILE *file = fopen("test.txt", "w");
if (file != NULL) {
// File operations here
int result = fclose(file);
if (result == 0) {
printf("File closed successfully\n");
} else {
printf("Error closing file\n");
}
}
if (file != NULL) {
// File operations here
int result = fclose(file);
if (result == 0) {
printf("File closed successfully\n");
} else {
printf("Error closing file\n");
}
}
5. Reading from Files
Functions for Reading:
fscanf()- Formatted readingfgets()- String readingfgetc()- Character readingfread()- Binary reading
Example: Reading with fscanf()
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
char name[50];
int age;
float salary;
while (fscanf(file, "%s %d %f", name, &age, &salary) != EOF) {
printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary);
}
fclose(file);
return 0;
}
int main() {
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
char name[50];
int age;
float salary;
while (fscanf(file, "%s %d %f", name, &age, &salary) != EOF) {
printf("Name: %s, Age: %d, Salary: %.2f\n", name, age, salary);
}
fclose(file);
return 0;
}
6. Writing to Files
Functions for Writing:
fprintf()- Formatted writingfputs()- String writingfputc()- Character writingfwrite()- Binary writing
Example: Writing with fprintf()
#include <stdio.h>
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fprintf(file, "This is a test file\n");
fprintf(file, "Number: %d, Float: %.2f\n", 42, 3.14159);
fclose(file);
printf("Data written successfully\n");
return 0;
}
int main() {
FILE *file = fopen("output.txt", "w");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
fprintf(file, "Hello, World!\n");
fprintf(file, "This is a test file\n");
fprintf(file, "Number: %d, Float: %.2f\n", 42, 3.14159);
fclose(file);
printf("Data written successfully\n");
return 0;
}
7. File Positioning
Functions:
fseek()- Sets file positionftell()- Returns current positionrewind()- Sets position to beginning
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("position.txt", "w+");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
fprintf(file, "Hello World!");
// Get current position
long position = ftell(file);
printf("Current position: %ld\n", position);
// Move to beginning
rewind(file);
// Read first 5 characters
char buffer[6];
fread(buffer, sizeof(char), 5, file);
buffer[5] = '\0';
printf("First 5 characters: %s\n", buffer);
fclose(file);
return 0;
}
int main() {
FILE *file = fopen("position.txt", "w+");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
fprintf(file, "Hello World!");
// Get current position
long position = ftell(file);
printf("Current position: %ld\n", position);
// Move to beginning
rewind(file);
// Read first 5 characters
char buffer[6];
fread(buffer, sizeof(char), 5, file);
buffer[5] = '\0';
printf("First 5 characters: %s\n", buffer);
fclose(file);
return 0;
}
8. Error Handling
Error Checking Functions:
feof()- Checks end-of-fileferror()- Checks file errorperror()- Prints error message
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
// Read until end of file or error
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
if (feof(file)) {
printf("\nEnd of file reached\n");
} else if (ferror(file)) {
perror("Error reading file");
}
fclose(file);
return EXIT_SUCCESS;
}
#include <stdlib.h>
int main() {
FILE *file = fopen("nonexistent.txt", "r");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
// Read until end of file or error
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
if (feof(file)) {
printf("\nEnd of file reached\n");
} else if (ferror(file)) {
perror("Error reading file");
}
fclose(file);
return EXIT_SUCCESS;
}
9. Binary File Operations
Reading and Writing Binary Data:
#include <stdio.h>
struct Student {
int id;
char name[50];
float gpa;
};
int main() {
// Write binary data
FILE *file = fopen("students.bin", "wb");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
struct Student s1 = {1, "John Doe", 3.8};
struct Student s2 = {2, "Jane Smith", 3.9};
fwrite(&s1, sizeof(struct Student), 1, file);
fwrite(&s2, sizeof(struct Student), 1, file);
fclose(file);
// Read binary data
file = fopen("students.bin", "rb");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
struct Student readStudent;
while (fread(&readStudent, sizeof(struct Student), 1, file) == 1) {
printf("ID: %d, Name: %s, GPA: %.2f\n",
readStudent.id, readStudent.name, readStudent.gpa);
}
fclose(file);
return 0;
}
struct Student {
int id;
char name[50];
float gpa;
};
int main() {
// Write binary data
FILE *file = fopen("students.bin", "wb");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
struct Student s1 = {1, "John Doe", 3.8};
struct Student s2 = {2, "Jane Smith", 3.9};
fwrite(&s1, sizeof(struct Student), 1, file);
fwrite(&s2, sizeof(struct Student), 1, file);
fclose(file);
// Read binary data
file = fopen("students.bin", "rb");
if (file == NULL) {
printf("Cannot open file\n");
return 1;
}
struct Student readStudent;
while (fread(&readStudent, sizeof(struct Student), 1, file) == 1) {
printf("ID: %d, Name: %s, GPA: %.2f\n",
readStudent.id, readStudent.name, readStudent.gpa);
}
fclose(file);
return 0;
}
10. File Management Functions
Additional File Functions:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Remove a file
if (remove("oldfile.txt") == 0) {
printf("File deleted successfully\n");
} else {
perror("Error deleting file");
}
// Rename a file
if (rename("temp.txt", "newfile.txt") == 0) {
printf("File renamed successfully\n");
} else {
perror("Error renaming file");
}
// Check if file exists
FILE *file = fopen("check.txt", "r");
if (file != NULL) {
printf("File exists\n");
fclose(file);
} else {
printf("File does not exist\n");
}
return 0;
}
#include <stdlib.h>
int main() {
// Remove a file
if (remove("oldfile.txt") == 0) {
printf("File deleted successfully\n");
} else {
perror("Error deleting file");
}
// Rename a file
if (rename("temp.txt", "newfile.txt") == 0) {
printf("File renamed successfully\n");
} else {
perror("Error renaming file");
}
// Check if file exists
FILE *file = fopen("check.txt", "r");
if (file != NULL) {
printf("File exists\n");
fclose(file);
} else {
printf("File does not exist\n");
}
return 0;
}
11. Complete Examples
Example: Student Records Management
#include <stdio.h>
#include <stdlib.h>
struct Student {
int rollno;
char name[50];
float marks;
};
void addStudent() {
FILE *file = fopen("students.dat", "ab");
if (file == NULL) {
printf("Cannot open file\n");
return;
}
struct Student s;
printf("Enter Roll No: ");
scanf("%d", &s.rollno);
printf("Enter Name: ");
scanf("%s", s.name);
printf("Enter Marks: ");
scanf("%f", &s.marks);
fwrite(&s, sizeof(struct Student), 1, file);
fclose(file);
printf("Student added successfully!\n");
}
void displayStudents() {
FILE *file = fopen("students.dat", "rb");
if (file == NULL) {
printf("No records found\n");
return;
}
struct Student s;
printf("\nStudent Records:\n");
printf("Roll No\tName\tMarks\n");
printf("----------------------\n");
while (fread(&s, sizeof(struct Student), 1, file) == 1) {
printf("%d\t%s\t%.2f\n", s.rollno, s.name, s.marks);
}
fclose(file);
}
int main() {
int choice;
do {
printf("\nStudent Record 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:
printf("Exiting...\n");
break;
default:
printf("Invalid choice\n");
}
} while (choice != 3);
return 0;
}
#include <stdlib.h>
struct Student {
int rollno;
char name[50];
float marks;
};
void addStudent() {
FILE *file = fopen("students.dat", "ab");
if (file == NULL) {
printf("Cannot open file\n");
return;
}
struct Student s;
printf("Enter Roll No: ");
scanf("%d", &s.rollno);
printf("Enter Name: ");
scanf("%s", s.name);
printf("Enter Marks: ");
scanf("%f", &s.marks);
fwrite(&s, sizeof(struct Student), 1, file);
fclose(file);
printf("Student added successfully!\n");
}
void displayStudents() {
FILE *file = fopen("students.dat", "rb");
if (file == NULL) {
printf("No records found\n");
return;
}
struct Student s;
printf("\nStudent Records:\n");
printf("Roll No\tName\tMarks\n");
printf("----------------------\n");
while (fread(&s, sizeof(struct Student), 1, file) == 1) {
printf("%d\t%s\t%.2f\n", s.rollno, s.name, s.marks);
}
fclose(file);
}
int main() {
int choice;
do {
printf("\nStudent Record 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:
printf("Exiting...\n");
break;
default:
printf("Invalid choice\n");
}
} while (choice != 3);
return 0;
}