02. Formatted Text File I/O in C
🟢 Difficulty: Beginner | fprintf(), fscanf(), Line-by-Line Reading & EOF Validation
📖 Definition
Formatted text file I/O in C uses functions like fprintf() and fscanf() to write and read human-readable, formatted text streams to and from a FILE* handle. Line-by-line text reading is handled via fgets().
🎯 Why It Is Used
- Structured Text Logging & Reports: Generating human-readable log files, configuration files (e.g. INI, CSV, JSON), and status reports.
- Parsing Formatted Tables: Reading space-separated or comma-separated text files into C variables.
⚙️ How It Works: Safe Loop Parsing
A common bug in C is using while (!feof(fp)) for file reading loops. feof() returns true only AFTER a read operation attempts to read past EOF and fails. This causes feof() loops to execute one extra duplicate iteration! Always test the return value of fscanf() or fgets() directly in the loop condition instead:
// CORRECT: Loop checks return count of successfully parsed fields!
while (fscanf(fp, "%d %31s %lf", &id, name, &gpa) == 3) {
// Process parsed record
}
📝 Syntax
#include <stdio.h>
// 1. Formatted Text Output
fprintf(file_ptr, "ID: %d | Name: %s\n", user_id, name_str);
// 2. Formatted Text Input (Returns count of matched specifiers)
int count = fscanf(file_ptr, "%d %31s", &user_id, name_str);
// 3. Line-by-Line Reading (Returns buffer pointer or NULL on EOF/error)
char line_buf[128];
while (fgets(line_buf, sizeof(line_buf), file_ptr) != NULL) {
// Process line
}
🔀 Text I/O Functions Summary
| Function | Operation | Return Value on Success | Return Value on Failure / EOF |
|---|---|---|---|
fprintf(fp, fmt, ...) | Formatted Write | Characters written count | Negative value |
fscanf(fp, fmt, ...) | Formatted Read | Input items matched count | EOF or less than expected items |
fputs(str, fp) | String Write | Non-negative integer | EOF |
fgets(buf, size, fp) | Line Read | Buffer pointer (buf) | NULL |
🌱 Beginner Example: Writing Formatted Student Records
#include <stdio.h>
int main(void) {
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) return 1;
fprintf(fp, "%d %s %.2lf\n", 101, "Alice", 3.85);
fprintf(fp, "%d %s %.2lf\n", 102, "Bob", 3.60);
fprintf(fp, "%d %s %.2lf\n", 103, "Charlie", 3.92);
fclose(fp);
printf("Wrote 3 student records to students.txt\n");
return 0;
}
🌼 Intermediate Example: Parsing Formatted Records with fscanf()
#include <stdio.h>
int main(void) {
FILE *fp = fopen("students.txt", "r");
if (fp == NULL) return 1;
int id;
char name[32];
double gpa;
printf("=== Parsed Student Records ===\n");
// fscanf returns the count of items successfully matched (3)
while (fscanf(fp, "%d %31s %lf", &id, name, &gpa) == 3) {
printf("ID: %d | Name: %-8s | GPA: %.2lf\n", id, name, gpa);
}
fclose(fp);
return 0;
}
🌲 Advanced Example: Safe Line-by-Line Config File Parser with fgets()
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("students.txt", "r");
if (fp == NULL) return 1;
char line[128];
int line_num = 1;
printf("=== Line-by-Line File Output ===\n");
while (fgets(line, sizeof(line), fp) != NULL) {
// Strip trailing newline if present
line[strcspn(line, "\r\n")] = '\0';
printf("Line #%d: %s\n", line_num++, line);
}
fclose(fp);
return 0;
}
🔍 Line-by-Line Explanation
fprintf(fp, "%d %s %.2lf\n", ...);: Formats text and writes it directly to the file stream.while (fscanf(fp, "%d %31s %lf", ...) == 3): Continues looping only while all 3 expected fields are successfully parsed. %31s prevents buffer overflow on 32-bytenamebuffer.while (fgets(line, sizeof(line), fp) != NULL): Reads up to 127 characters or until newline safely.
💻 Expected Terminal Output
Wrote 3 student records to students.txt
=== Parsed Student Records ===
ID: 101 | Name: Alice | GPA: 3.85
ID: 102 | Name: Bob | GPA: 3.60
ID: 103 | Name: Charlie | GPA: 3.92
=== Line-by-Line File Output ===
Line #1: 101 Alice 3.85
Line #2: 102 Bob 3.60
Line #3: 103 Charlie 3.92
⚠️ Common Mistakes & Pitfalls
- Using
while (!feof(fp)): Callingfeof()as a loop condition causes the last line of the file to be processed twice! Always checkfscanf() == countorfgets() != NULLinstead. - Unbounded
%sSpecifier infscanf: Writingfscanf(fp, "%s", name)without length limits allows long input lines to overflow thenamebuffer. Use%31s.
📌 Important Rules & Limitations
- Always validate the return value of
fscanf()against expected parameter match counts. - Never use
while (!feof(fp))for file loop conditions.
🌐 Multilingual Explanation: English
Use fprintf() for formatted text writing, fscanf() for parsing specifiers, and fgets() for line-by-line reading. Test function return values directly rather than using feof().
🌐 Multilingual Explanation: Hindi (Roman Script)
Formatted text ke liye fprintf() aur fscanf() ka upyog karein. File padhne wale loops mein while (!feof(fp)) ke bajaye fscanf() == count check karein.
🌐 Multilingual Explanation: Marathi (Roman Script)
Text files vachnyasathi fgets() aani parse karnyasathi fscanf() vapartat. Loop madhye feof() peksha return value check kara.
❓ Practice Questions
- Why does
while (!feof(fp))cause the final record in a file to be processed twice? - How does specifying
%31sinfscanf()prevent buffer overflow vulnerabilities? - What value does
fscanf()return when it reaches the end of a file?
🚀 Practical Coding Challenge
Write a C program named log_analyzer.c that opens a text log file, uses fgets and strstr to search for lines containing the word "ERROR", and writes those matching lines to a separate errors.log file.
🧭 Navigation & Breadcrumbs
← Previous: 01. File Streams | Module 16 Guide | Next: 03. Binary File I/O →