Text File Processing

Text File Processing in C: Opening a file gives you a — a handle to an open drawer, with a bookmark resting between two characters.

The Analogy: A Drawer With a Bookmark In It

Opening a file gives you a FILE * — a handle to an open drawer, with a bookmark resting between two characters. Every read moves the bookmark forward by exactly what you consumed; every write drops characters at the bookmark and pushes it along. You never see the bookmark, but almost every file bug comes from being wrong about where it is.

Two things follow from the drawer image, and they are the ones beginners skip. Opening can fail — the drawer may be locked, missing, or in a room you have no key to — so fopen returns NULL and you must check it before touching the handle. And closing is not a formality: what you "wrote" may still be sitting in a buffer in memory, so fclose is where the last of it actually reaches the disk, which is why fclose has a return value worth checking.


Syntax or Core Structure

#include <stdio.h>

int main(void) {
    FILE *out = fopen("notes.txt", "w");        /* creates or truncates */
    if (out == NULL) { perror("notes.txt"); return 1; }

    fprintf(out, "alpha 10\n");
    fprintf(out, "beta 20\n");
    fprintf(out, "gamma 30\n");

    if (fclose(out) != 0) { perror("closing notes.txt"); return 1; }

    FILE *in = fopen("notes.txt", "r");
    if (in == NULL) { perror("notes.txt"); return 1; }

    char line[128];
    int lineno = 0;
    while (fgets(line, sizeof line, in) != NULL)
        printf("%2d: %s", ++lineno, line);      /* line still ends in a newline */

    if (ferror(in)) {                           /* the loop ended badly, not at EOF */
        fprintf(stderr, "read failed\n");
        fclose(in);
        return 1;
    }
    fclose(in);
    return 0;
}

Output:

 1: alpha 10
 2: beta 20
 3: gamma 30

Notice the printf has no \n of its own: fgets keeps the newline it read, so adding another would double-space the output. That single detail catches almost everyone once.

The modes

ModeIf the file existsIf it does notBookmark startsCan readCan write
"r"opened as-isfailsstartyesno
"w"truncated to emptycreatedstartnoyes
"a"opened, keptcreatedend, and every write goes to the endnoyes
"r+"opened as-isfailsstartyesyes
"w+"truncated to emptycreatedstartyesyes
"a+"opened, keptcreatedreads from start, writes at endyesyes

"w" destroying an existing file is the most expensive mistake in this table. If you mean "add to it", the mode is "a". Append also has a useful guarantee: each write lands at the current end of file, so two processes appending lines will not overwrite each other mid-line.

Adding b — "rb", "wb" — selects binary mode, which is the next lesson's subject. In text mode on Windows, \n is translated to a two-byte line ending on the way out and back on the way in; on Linux and macOS the modes are identical. That translation is exactly why counting bytes in a text file is unreliable.


Technical Depth: Reading Lines Without Getting Hurt

FunctionReadsStops atWatch out for
fgetcone character—returns int, not char, so EOF is distinguishable
fgetsa linenewline, size - 1 chars, or EOFkeeps the newline; truncates silently on long lines
fscanfformatted fieldsfirst mismatchleaves the offending text in the stream
sscanfformatted fields, from a stringfirst mismatchsafe to retry, because the string does not move
fprintf——same format rules as printf
fputs——does not add a newline

The workhorse pattern for reading data is not fscanf — it is fgets to get one line, then sscanf to pick it apart. fscanf reading straight from the file leaves malformed input sitting in the stream, so the next call fails on the same characters and your loop spins forever. With fgets the line is already consumed; a parse failure costs you one record and the loop moves on.

Stripping the newline

#include <string.h>

char line[128];
if (fgets(line, sizeof line, in) != NULL) {
    line[strcspn(line, "\n")] = '\0';        /* trims the newline if present */
}

strcspn returns the index of the first newline, or the length of the string if there is none — so this one line works on the final line of a file that has no trailing newline. The obvious alternative, line[strlen(line) - 1] = '\0', deletes a real character in that case, and reads out of bounds on an empty string.

Detecting a line that did not fit

if (strchr(line, '\n') == NULL && !feof(in)) {
    /* the line was longer than the buffer; the rest is still in the stream */
}

fgets never overruns the buffer, but it also never tells you it truncated. Without this check, a 200-character line in a 128-byte buffer quietly becomes two records, and your parser reports a mysterious malformed row.

The while (!feof(f)) bug

/* Wrong: processes the last line twice, or a garbage line once. */
while (!feof(in)) {
    fgets(line, sizeof line, in);
    process(line);
}

/* Right: the read itself is the loop condition. */
while (fgets(line, sizeof line, in) != NULL)
    process(line);

feof only becomes true after a read has already failed by hitting the end. At the top of the final iteration it is still false, so the loop body runs one more time on a failed read and re-processes whatever was left in line. Test the return value of the read, then use feof and ferror afterwards to ask why it stopped:

if (ferror(in)) { /* a real I/O error */ }
else if (feof(in)) { /* a clean end of file */ }

gets does not exist

It was removed from the language in C11 because it had no way to know the size of your buffer. If you find it in old code or a tutorial, replace it with fgets(buf, sizeof buf, stdin) — there is no situation in which gets is the right call.

Why fclose can fail

Writes are buffered. fclose flushes the buffer, and that flush is where a full disk or a network drop finally surfaces. A program that ignores fclose's return value can print "saved successfully" over a file that is missing its last few kilobytes. Use fflush if you need the data on disk before closing — for instance, before a long computation that might crash.


Real World Example: Parsing an Inventory File That Is Not Perfectly Clean

Real data files have comment lines, blank lines, and at least one row someone typed by hand. A loader that survives all three looks like this. Given inventory.csv:

# id,name,qty,price
101,bolt,250,0.35
102,nut,480,0.20

103,washer,oops,0.10
104,bracket,30,4.75
#include <stdio.h>
#include <string.h>

#define MAX_ITEMS 64

struct Item { int id; char name[16]; int quantity; double price; };

int main(void) {
    FILE *in = fopen("inventory.csv", "r");
    if (in == NULL) { perror("inventory.csv"); return 1; }

    struct Item items[MAX_ITEMS];
    size_t count = 0;
    int lineno = 0, bad = 0, first_bad = 0;
    char line[256];

    while (fgets(line, sizeof line, in) != NULL) {
        lineno++;

        if (strchr(line, '\n') == NULL && !feof(in)) {
            fprintf(stderr, "line %d is too long, skipped\n", lineno);
            bad++;
            continue;                      /* the remainder is read as its own line */
        }

        line[strcspn(line, "\n")] = '\0';
        if (line[0] == '#' || line[0] == '\0') continue;   /* comment or blank */

        struct Item it;
        if (sscanf(line, "%d,%15[^,],%d,%lf",
                   &it.id, it.name, &it.quantity, &it.price) != 4) {
            if (bad == 0) first_bad = lineno;
            bad++;
            continue;
        }

        if (count == MAX_ITEMS) { fprintf(stderr, "table full\n"); break; }
        items[count++] = it;
    }

    if (ferror(in)) { perror("reading inventory.csv"); fclose(in); return 1; }
    fclose(in);

The parse succeeded only when sscanf reports 4 conversions — that count is the whole validity check, and it is why the return value must never be ignored. %15[^,] reads up to 15 characters that are not a comma, leaving room for the terminator in a 16-byte field.

Now print the table and write the same figures to a report:

    double total = 0.0;
    for (size_t i = 0; i < count; i++) {
        double value = items[i].quantity * items[i].price;
        total += value;
        printf("%3d  %-10s %5d %8.2f %9.2f\n", items[i].id, items[i].name,
               items[i].quantity, items[i].price, value);
    }

    printf("\n%zu rows, %d malformed", count, bad);
    if (bad > 0) printf(" (line %d)", first_bad);
    printf("\nstock value: %.2f\n", total);

    FILE *rep = fopen("report.txt", "w");       /* truncates any old report */
    if (rep == NULL) { perror("report.txt"); return 1; }
    fprintf(rep, "items=%zu malformed=%d value=%.2f\n", count, bad, total);
    if (fclose(rep) != 0) { perror("writing report.txt"); return 1; }

    printf("wrote report.txt\n");
    return 0;
}

Output:

101  bolt         250     0.35     87.50
102  nut          480     0.20     96.00
104  bracket       30     4.75    142.50

3 rows, 1 malformed (line 5)
stock value: 326.00
wrote report.txt

Line 5 is 103,washer,oops,0.10: %d cannot read oops, so sscanf stops after two conversions, returns 2, and the record is rejected. The comment on line 1 and the blank line 4 are skipped before parsing is even attempted, so they are not counted as errors — a distinction worth keeping, because "3 rows, 1 malformed" is an actionable message and "3 rows, 3 skipped" is not.

Four choices make this robust rather than merely working:

  1. fgets then sscanf. A bad line costs one record. With fscanf straight from the file, oops would still be in the stream and the loop would never advance past it.
  2. The line number is tracked separately from the record count. When a user has to fix the file, they need the line, not "record 3".
  3. Truncation is detected, not assumed away. A 300-character line in a 256-byte buffer is reported instead of silently splitting into two half-records.
  4. Both fclose calls are checked on the write path. The report is the output someone will trust; a silent flush failure there is worse than no report at all.

Common Mistakes

  1. Not checking fopen. Using a NULL FILE * crashes immediately. Check it every time, and use perror("filename") so the message names both the file and the reason.
  2. Using "w" when you meant "a". "w" truncates an existing file to zero bytes the moment it opens, before you write anything. The old contents are gone.
  3. while (!feof(f)). feof turns true only after a read has already failed, so the body runs once too often on stale buffer contents. Put the read in the condition.
  4. Forgetting that fgets keeps the newline. Printing with an extra \n double-spaces, and comparing with strcmp(line, "quit") fails because the line is really "quit\n".
  5. Trimming with line[strlen(line) - 1] = '\0'. On a final line with no newline it deletes a real character, and on an empty string it writes to index -1. Use strcspn.
  6. Ignoring sscanf's return value. It reports how many conversions succeeded; on a short count the remaining variables are untouched, so the record is filled with whatever was on the stack.
  7. Assuming every line fits the buffer. fgets will not overflow, but it truncates silently and the remainder arrives as a bogus extra line. Check for the newline.
  8. Ignoring fclose's return value on files you wrote. The buffered flush happens there; a disk-full error reported nowhere else surfaces as a -1 from fclose.

Best Practices

  • Check fopen, then ferror after the loop, then fclose — three checks that turn a silent corruption into a message.
  • Read with fgets and parse with sscanf. Reserve fscanf for throwaway programs where malformed input cannot happen.
  • Width-limit every %s and %[ conversion (%15[^,]) to one less than the buffer size.
  • Strip the newline once, immediately after reading, with line[strcspn(line, "\n")] = '\0'.
  • Close every file on every exit path, including the error paths — one fclose before each return, or a single cleanup label.
  • Report the line number with every parse failure, and keep counting instead of stopping at the first bad row.
  • Never use "w" on a file you were asked to update; write to a temporary file and rename it if you need to replace one safely.
  • Treat text mode as "characters, not bytes" — do not compute file sizes or seek by arithmetic in text mode.

Practice Exercises

  1. A word and line counter. Write a program that opens a file named on argv[1], then reports lines, words and characters — the essentials of wc. Count a word as a run of non-space characters. Handle a file whose last line has no trailing newline, and verify your figures against a file you wrote by hand with a known count. Print a usage message and return 1 when argc != 2.
  2. Line numbering with truncation detection. Read a file with a deliberately small char line[16] buffer and print each line prefixed by its number. Detect truncated reads with the strchr check and mark them, so a 40-character line is reported as one long line rather than three short ones. Compare your output against the same program with char line[256].
  3. Append versus truncate, demonstrated. Write a program that takes a mode string and a message and calls fopen(path, mode), then fprintfs the message. Run it with "a" three times and cat the file; run it once with "w" and cat again. Write down exactly what the file contains after each step, then explain in one sentence what "a" guarantees that "w" does not.
  4. Harden the inventory loader. Extend the example so it rejects rows with a negative quantity or a price below zero, counts those separately from parse failures, and reports the first offending line number of each kind. Then add a duplicate-id check that prints a warning and keeps the first occurrence. Feed it a file containing one of each problem and confirm the counts match what you put in.