-
Hajipur, Bihar, 844101
In C programming, file handling allows a program to store and retrieve data permanently. While variables in memory exist only during program execution, files provide persistent storage on disk. This makes file handling essential for applications such as databases, logging systems, and data processing programs.
C provides a set of standard functions in the stdio.h library to work with files, enabling reading, writing, and updating data efficiently.
Files in C can be categorized as:
Text Files: Store data as human-readable text. Each line ends with a newline character \n.
Binary Files: Store data in binary format, which is more efficient for storage and retrieval but not human-readable.
Choosing between text and binary files depends on the nature of data and required efficiency.
Before reading or writing a file, it must be opened using the fopen() function:
FILE *fopen(const char *filename, const char *mode);
filename: Name of the file (can include path).
mode: Defines the file operation, such as reading, writing, or appending.
Common file modes:
| Mode | Description |
|---|---|
"r" |
Read (file must exist) |
"w" |
Write (creates file or overwrites) |
"a" |
Append (writes at end, creates file if needed) |
"r+" |
Read and write (file must exist) |
"w+" |
Write and read (creates or overwrites) |
"a+" |
Append and read (creates if needed) |
Example:
#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "w");
if(file == NULL) {
printf("Error opening file.\n");
return 1;
}
fprintf(file, "Hello, C file handling!\n");
fclose(file);
return 0;
}
Opens data.txt for writing.
fprintf() writes text to the file.
fclose() closes the file and frees system resources.
C provides several functions to write data to a file:
fprintf(FILE *fp, "format", ...) – formatted output to file.
fputs(const char *str, FILE *fp) – writes a string to file.
fputc(int c, FILE *fp) – writes a single character.
Example:
FILE *file = fopen("output.txt", "w");
fprintf(file, "Name: Alice\nAge: 25\n");
fputs("This is a second line.\n", file);
fputc('X', file);
fclose(file);
C provides multiple ways to read file content:
fscanf(FILE *fp, "format", ...) – reads formatted data.
fgets(char *str, int n, FILE *fp) – reads a line (up to n-1 characters).
fgetc(FILE *fp) – reads a single character.
Example:
FILE *file = fopen("output.txt", "r");
char line[100];
while(fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
Reads file line by line until end of file (EOF).
fgets() prevents buffer overflow by limiting characters read.
The feof(FILE *fp) function checks whether the end of a file has been reached.
int c;
FILE *file = fopen("output.txt", "r");
while((c = fgetc(file)) != EOF) {
putchar(c);
}
if(feof(file))
printf("\nEnd of file reached.\n");
fclose(file);
EOF is a constant indicating the end of file.
feof() can be used for conditional checks when reading.
After operations, always close the file using fclose(FILE *fp).
fclose(file);
Ensures data is written to disk.
Frees system resources associated with the file.
Failure to close a file can cause data loss or memory leaks.
To add data without overwriting existing content, use append mode "a":
FILE *file = fopen("output.txt", "a");
fprintf(file, "Appending a new line.\n");
fclose(file);
Existing data remains intact.
New data is added at the end of the file.
Always check if a file is opened successfully:
FILE *file = fopen("nonexistent.txt", "r");
if(file == NULL) {
perror("File open error");
return 1;
}
fopen() returns NULL if the file cannot be opened.
perror() prints a system-generated error message.
#include <stdio.h>
int main() {
FILE *file = fopen("students.txt", "w");
if(file == NULL) {
printf("Unable to create file.\n");
return 1;
}
fprintf(file, "Name: Alice, Age: 20\n");
fprintf(file, "Name: Bella, Age: 22\n");
fclose(file);
// Reading the file
char line[100];
file = fopen("students.txt", "r");
if(file == NULL) return 1;
printf("File contents:\n");
while(fgets(line, sizeof(line), file) != NULL) {
printf("%s", line);
}
fclose(file);
return 0;
}
Demonstrates writing multiple lines and reading them back.
Uses fprintf() for writing and fgets() for reading.
File handling in C is essential for persistent data storage. By using FILE* pointers and functions like fopen(), fclose(), fprintf(), fscanf(), fgets(), and fgetc(), programmers can read, write, and update files efficiently. Proper error checking, closing files, and choosing the right mode ensures data integrity and program stability. Mastery of file handling is crucial for data-driven applications, logs, and real-world programs in C.
Write a program to create a text file and write your name and age into it.
Create a program to read the content of a text file line by line and display it on the screen.
Write a program to append new data to an existing file without deleting the old content.
Develop a program to count the number of lines in a given text file.
Write a program to copy the contents of one file into another file.
Create a program to read a file character by character and display each character.
Write a program that checks if a file exists and prints an appropriate message.
Develop a program to write integers from 1 to 10 into a file and then read them back.
Write a program to read a file and count the number of words in it.
Create a program to write student details (name, age, grade) into a file and read them back to display in a formatted table.