File Handling: Reading and Writing Files
Permanent data storage in C requires file streams using standard library file pointers.
What is it?
File I/O in C operates through the `FILE*` stream pointer defined in `<stdio.h>`.
Why is it used?
Saving student records, loading configuration settings, generating invoices, and logging server events.
Detailed Explanation
File Functions:
• `fopen(filename, mode)`: Opens file. Modes include `"r"` (read), `"w"` (write/create), `"a"` (append), `"rb"`/`"wb"` (binary).
• `fclose(file_ptr)`: Closes file stream and flushes write buffer.
• `fprintf(file_ptr, format, ...)`: Writes formatted text to file.
• `fscanf(file_ptr, format, ...)`: Reads formatted text from file.
• `fgets(buffer, size, file_ptr)`: Safely reads a line of text.
• Always verify `if (fp == NULL)` to handle missing files.
Syntax Structure
Syntax Blueprint
FILE *fp = fopen("data.txt", "w");
if (fp != NULL) {
fprintf(fp, "Hello File\n");
fclose(fp);
}
Code Example
C Code
#include <stdio.h>
int main() {
const char *filepath = "igm_students.txt";
// 1. Writing records to file
FILE *fp = fopen(filepath, "w");
if (fp == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fprintf(fp, "101,Rohan Sharma,Python\n");
fprintf(fp, "102,Sneha Patil,Excel\n");
fprintf(fp, "103,Amit Joshi,DataAnalytics\n");
fclose(fp);
printf("Successfully saved 3 records to '%s'.\n", filepath);
// 2. Reading records back from file line by line
FILE *read_fp = fopen(filepath, "r");
if (read_fp == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
printf("\n--- Stored Records ---\n");
char buffer[128];
while (fgets(buffer, sizeof(buffer), read_fp) != NULL) {
printf("Record: %s", buffer);
}
fclose(read_fp);
return 0;
}
Explanation of the Code
• `fopen(..., "w")` creates the file on disk.
• `fprintf()` writes formatted CSV data.
• `fgets()` reads file line-by-line safely without buffer overflow risks.
• Always closes files with `fclose()`.
Expected Output
Successfully saved 3 records to 'igm_students.txt'.
--- Stored Records ---
Record: 101,Rohan Sharma,Python
Record: 102,Sneha Patil,Excel
Record: 103,Amit Joshi,DataAnalytics
Real-World Application
Used across database storage engines (like SQLite itself, written in C) to read and write database pages to disk.
Common Mistakes to Avoid
• Forgetting to call `fclose()`, causing corrupted or partially written files due to unflushed buffers.
• Not checking if `fopen` returned `NULL` before attempting to read.
Quick Practice Challenge
Open a file in `'a'` mode and append a student record to the end of `igm_students.txt`.
Key Takeaways
• File I/O uses `FILE*` pointer streams.
• Always verify `if (fp == NULL)` after calling `fopen()`.
• Always close file streams with `fclose()` to flush buffers.