C — File Handling
Opening and closing files
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}
fprintf(fp, "Hello, file!\n");
fclose(fp);
printf("File written successfully\n");
return 0;
}
File modes
| Mode | Description |
|---|---|
"r" | Read (file must exist) |
"w" | Write (creates or truncates) |
"a" | Append (creates if needed) |
"r+" | Read + write (file must exist) |
"w+" | Read + write (creates or truncates) |
"a+" | Read + append (creates if needed) |
"rb" | Read binary |
"wb" | Write binary |
Writing to files
#include <stdio.h>
int main() {
FILE *fp = fopen("output.txt", "w");
if (!fp) {
perror("Error");
return 1;
}
// fprintf: formatted output
fprintf(fp, "Name: %s\n", "Alice");
fprintf(fp, "Score: %d\n", 95);
fprintf(fp, "Average: %.2f\n", 92.5);
// fputs: write a string
fputs("This is a line\n", fp);
// fputc: write a single character
fputc('A', fp);
fputc('\n', fp);
fclose(fp);
return 0;
}
Reading from files
#include <stdio.h>
#include <stdlib.h>
int main() {
// Write test data first
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Alice 95\n");
fprintf(fp, "Bob 87\n");
fprintf(fp, "Charlie 92\n");
fclose(fp);
// Read it back
fp = fopen("data.txt", "r");
if (!fp) {
perror("Error");
return 1;
}
char name[50];
int score;
// fscanf: formatted input
while (fscanf(fp, "%s %d", name, &score) == 2) {
printf("Name: %s, Score: %d\n", name, score);
}
fclose(fp);
return 0;
}
Reading line by line
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp = fopen("lines.txt", "w");
fprintf(fp, "First line\n");
fprintf(fp, "Second line\n");
fprintf(fp, "Third line\n");
fclose(fp);
fp = fopen("lines.txt", "r");
char buffer[256];
int lineNum = 0;
// fgets: read one line at a time (recommended)
while (fgets(buffer, sizeof(buffer), fp) != NULL) {
lineNum++;
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = '\0';
printf("Line %d: %s\n", lineNum, buffer);
}
fclose(fp);
return 0;
}
Reading entire file
#include <stdio.h>
#include <stdlib.h>
char *readFile(const char *filename) {
FILE *fp = fopen(filename, "r");
if (!fp) return NULL;
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
rewind(fp);
char *buffer = malloc(size + 1);
if (!buffer) {
fclose(fp);
return NULL;
}
fread(buffer, 1, size, fp);
buffer[size] = '\0';
fclose(fp);
return buffer;
}
int main() {
char *content = readFile("data.txt");
if (content) {
printf("File contents:\n%s\n", content);
free(content);
}
return 0;
}
Binary file I/O
#include <stdio.h>
typedef struct {
char name[50];
int age;
float score;
} Record;
int main() {
Record records[] = {
{"Alice", 30, 95.5f},
{"Bob", 25, 87.0f},
{"Charlie", 35, 92.3f}
};
int count = sizeof(records) / sizeof(records[0]);
// Write binary
FILE *fp = fopen("records.bin", "wb");
fwrite(records, sizeof(Record), count, fp);
fclose(fp);
// Read binary
Record readRecords[3];
fp = fopen("records.bin", "rb");
fread(readRecords, sizeof(Record), count, fp);
fclose(fp);
for (int i = 0; i < count; i++) {
printf("%s: %d, %.1f\n",
readRecords[i].name,
readRecords[i].age,
readRecords[i].score);
}
return 0;
}
File position
#include <stdio.h>
int main() {
FILE *fp = fopen("pos.txt", "w+");
fprintf(fp, "ABCDEFGHIJ");
// ftell: current position
printf("Position: %ld\n", ftell(fp)); // 10
// fseek: move to position
fseek(fp, 0, SEEK_SET); // Beginning
printf("Position: %ld\n", ftell(fp)); // 0
fseek(fp, 5, SEEK_SET); // 5 bytes from start
char c = fgetc(fp);
printf("Char at 5: %c\n", c); // F
fseek(fp, -3, SEEK_END); // 3 bytes before end
c = fgetc(fp);
printf("Char at end-3: %c\n", c); // H
fclose(fp);
return 0;
}
Error checking
#include <stdio.h>
int main() {
FILE *fp = fopen("nonexistent.txt", "r");
if (fp == NULL) {
perror("Error opening file");
// Or: fprintf(stderr, "Error: %s\n", strerror(errno));
return 1;
}
// Check for read errors
int c;
while ((c = fgetc(fp)) != EOF) {
putchar(c);
}
if (ferror(fp)) {
fprintf(stderr, "Error reading file\n");
}
fclose(fp);
return 0;
}
Mini Practice
Write C code that:
- Writes a list of names and scores to a file
- Reads the file back and calculates the average score
- Copies a file line by line to another file
- Writes and reads a binary file containing structs
Up Next
In the next lesson, you'll learn about Memory Management — malloc, calloc, realloc, and free.
Related Topics
Frequently Asked Questions about File Handling
What is File Handling in C?
File Handling is a fundamental concept in C. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn File Handling?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn File Handling.
Why is File Handling important in C?
File Handling is essential for C development. Understanding this concept will help you write better code and solve real-world problems more effectively.