Thuta Learning
C
AdvancedProgrammingBeginner

File I/O

CLesson 2430 min

What you'll walk away with

  • Know why fopen() can return NULL and report the reason with perror()
  • Pick between "r", "w", "a" and their "+" and "b" variants for the job at hand
  • Read a file line by line with an fgets() loop and tell end of file from a read error with feof() and ferror()
  • Explain why buffering makes fclose()'s return value worth checking
  • Describe how text mode translates '\n' on Windows and use "rb"/"wb" for binary data

Explain it simply

Explain it simply

Data in variables vanishes the moment the program ends. To keep scores, settings or logs until the next run, you write them to a file on disk.

Working with a file in C is like borrowing a library book: fopen() borrows it (and says whether you will read or write), fprintf() and fgets() use it, and fclose() returns it. The book may not exist, or you may not be allowed to borrow it, so you always check whether the borrowing worked.

Problem → Why → Solution

The problem: works on your machine, breaks on a friend's

The program below reads the first line of settings.txt. Run from the project folder, it works perfectly. A friend runs it from a different folder, or the file has been renamed, and fopen() returns NULL. A MinGW build on Windows then printed garbage characters, while on Linux the same code typically crashes with a segmentation fault. -Wall -Wextra produce no warning at all.

settings_bug.c
#include <stdio.h>

int main(void) {
    FILE *f = fopen("settings.txt", "r");   /* NULL if the file is missing */
    char line[100];
    fgets(line, sizeof line, f);            /* f may be NULL here */
    printf("first setting: %s", line);
    fclose(f);
    return 0;
}

What went wrong?

A relative path like "settings.txt" is resolved against the current working directory, the folder the program was started from, not the folder where the executable lives. When the file is not found, fopen() returns NULL and stores the reason in errno, but this program never checks and passes NULL straight to fgets(). Check fopen() every time, and perror("settings.txt") prints a message such as "settings.txt: No such file or directory" that explains the problem instantly.

Core concept: FILE streams, modes and buffers

fopen(path, mode) returns a FILE * (a stream), and every read and write function takes that pointer. fopen() returns NULL when the file is missing, permission is denied, the folder does not exist or too many files are already open. "r" reads an existing file, "w" writes (creating the file, or wiping its contents the moment fopen runs), and "a" appends to the end. Adding "+" allows both reading and writing. Choose the mode deliberately, because it decides whether merely opening the file destroys what is already in it.

fprintf() and fputs() do not write to the disk directly; they collect bytes in a memory buffer first. The data reaches the file only when the buffer fills up, when you call fflush(), or when you call fclose(). So if the disk is full, the error may surface at fclose rather than at fprintf, which is why fclose(f) == EOF deserves a check. If the program crashes before fclose, the last buffered data can be lost.

For reading, use the loop while (fgets(line, sizeof line, f) != NULL). fgets returns NULL both at end of file and on an error, so after the loop, ferror(f) tells the two apart. Each line also keeps its '\n', so strip it before comparing the text with strcmp.

Text and binary mode are identical on Linux and macOS. On Windows, text mode ("r", "w") turns each '\n' into the two bytes "\r\n" when writing, and back again when reading. That is fine for text, but it corrupts data that must stay byte-exact: images, zip files, numbers written with fwrite(). Use "rb" and "wb" for such data so the bytes are left untouched.

Mental model: borrow, use, give back
  1. fopen with a mode, check for NULL
  2. fprintf/fgets go through a buffer
  3. After the loop, check ferror()
  4. fclose flushes; check it for EOF

Every step can fail, so every return value deserves a check.

General pattern

c
FILE *f = fopen(path, mode);          /* "r", "w", "a", "rb", "wb", ... */
if (f == NULL) {
    perror(path);                       /* explains why */
    return EXIT_FAILURE;
}
/* fprintf(f, ...) / fgets(buf, sizeof buf, f) / fread / fwrite */
if (fclose(f) == EOF) {
    /* buffered data may not have reached the file */
}

Open, check for NULL, use, close and check the close: the order is the same for every file. Only the mode and the read or write calls in the middle change.

Example: writing scores and reading them back

This program creates scores-demo.txt in the current directory, writes three lines and closes it. It then reopens the file, reads it line by line and computes the average score. Finally remove() deletes the demo file, so nothing is left behind; comment that line out if you want to open the file yourself.

scores_file.c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *path = "scores-demo.txt";   /* relative to the current directory */

    /* 1. Write: "w" creates the file, or empties it if it exists */
    FILE *out = fopen(path, "w");
    if (out == NULL) {
        perror(path);
        return EXIT_FAILURE;
    }
    fprintf(out, "Aye 82\n");
    fprintf(out, "Ko 91\n");
    fprintf(out, "Su 77\n");
    if (fclose(out) == EOF) {               /* flushes the buffer to the file */
        perror("fclose");
        return EXIT_FAILURE;
    }

    /* 2. Read it back, one line at a time */
    FILE *in = fopen(path, "r");
    if (in == NULL) {
        perror(path);
        return EXIT_FAILURE;
    }
    char line[100];
    int count = 0, total = 0;
    while (fgets(line, sizeof line, in) != NULL) {
        char name[32];
        int score;
        if (sscanf(line, "%31s %d", name, &score) == 2) {
            printf("%-4s %3d\n", name, score);
            total += score;
            count++;
        }
    }
    int status = EXIT_SUCCESS;
    if (ferror(in)) {                       /* NULL meant error, not end of file */
        perror("read");
        status = EXIT_FAILURE;
    }
    fclose(in);
    remove(path);                           /* delete the demo file again */

    if (count > 0) {
        printf("average: %.1f\n", (double)total / count);
    }
    return status;
}

Code breakdown

  1. Open for writingFILE *out = fopen(path, "w");

    "w" creates the file if it is missing and erases any old contents right here, at fopen. Use "a" when existing data must be kept.

  2. Report the reasonperror(path);

    Prints the reason stored in errno to stderr, in a form like "scores-demo.txt: Permission denied", so the user sees which file failed and why.

  3. Close and flushif (fclose(out) == EOF) { /* flushes the buffer to the file */

    The three fprintf calls may still be sitting in the buffer; fclose writes them out. If it fails here, the data may never have reached the file.

  4. Read loopwhile (fgets(line, sizeof line, in) != NULL) {

    fgets reads one line, '\n' included, and returns NULL at the end, so the loop runs exactly as often as needed. sscanf then splits out name and score, and %31s keeps the name within name[32].

  5. Error or end?if (ferror(in)) { /* NULL meant error, not end of file */

    Decides whether the loop ended because the file ended or because reading failed. On an error, the program's exit status becomes EXIT_FAILURE.

  6. Clean upremove(path); /* delete the demo file again */

    remove() deletes the file and returns 0 on success. Note that it runs after fclose; on Windows, a file that is still open usually cannot be deleted.

You should see
Aye   82
Ko    91
Su    77
average: 83.3

The modes at a glance

ModeIf the file is missingIf the file exists
"r"Returns NULLReads from the start
"w"Creates itErases everything, then writes
"a"Creates itWrites at the end
"r+"Returns NULLRead and write, nothing erased
"w+" / "a+"Creates itLike "w" / "a", reading allowed too
"wx" (C11)Creates itReturns NULL instead of overwriting

Any mode can take a b ("rb", "wb", "ab", "r+b"). C11's "wx" is supported by glibc and Microsoft's UCRT, but the older msvcrt.dll runtime used by some MinGW toolchains rejects it with "Invalid argument", as a w64devkit GCC 16 build showed.

Seeing text versus binary mode for yourself

The program below writes "one\ntwo\n" once with "w" and once with "wb", then counts the bytes on disk using "rb". On Windows, "w" gives 10 bytes (each newline became \r\n) and "wb" gives 8; on Linux and macOS both give 8.

text_vs_binary.c
#include <stdio.h>

/* Counts a file's bytes, reading in binary mode so nothing is translated. */
long count_bytes(const char *path) {
    FILE *f = fopen(path, "rb");
    if (f == NULL) {
        return -1;
    }
    long n = 0;
    while (fgetc(f) != EOF) {
        n++;
    }
    fclose(f);
    return n;
}

int main(void) {
    const char *path = "mode-demo.txt";
    const char *modes[] = {"w", "wb"};

    for (int i = 0; i < 2; i++) {
        FILE *f = fopen(path, modes[i]);
        if (f == NULL) {
            perror(path);
            return 1;
        }
        fputs("one\ntwo\n", f);
        if (fclose(f) == EOF) {
            perror("fclose");
            return 1;
        }
        printf("mode \"%s\": %ld bytes on disk\n", modes[i], count_bytes(path));
    }
    remove(path);
    return 0;
}

For binary data, pair fwrite() and fread() with "wb" and "rb". Both return how many items were actually transferred, so compare that with what you asked for. The bytes of 2560 include 0x0A ('\n'), exactly the kind of value Windows text mode would corrupt. Also keep in mind that a file of raw ints can only be read back on machines with the same byte order and int size.

binary_numbers.c
#include <stdio.h>

int main(void) {
    const char *path = "numbers-demo.bin";
    int data[] = {10, 2560, -1, 42};
    size_t n = sizeof data / sizeof data[0];

    FILE *f = fopen(path, "wb");
    if (f == NULL) {
        perror(path);
        return 1;
    }
    size_t written = fwrite(data, sizeof data[0], n, f);
    if (fclose(f) == EOF || written != n) {
        perror("write");
        remove(path);
        return 1;
    }

    int back[4];
    f = fopen(path, "rb");
    if (f == NULL) {
        perror(path);
        return 1;
    }
    size_t got = fread(back, sizeof back[0], n, f);
    fclose(f);
    remove(path);

    printf("read %d of %d ints:", (int)got, (int)n);
    for (size_t i = 0; i < got; i++) {
        printf(" %d", back[i]);
    }
    printf("\n");
    return 0;
}

In real projects

Where this shows up in real projects

Servers append every event to a log file in "a" mode; opening it with "w" would wipe the old log on every restart. Command-line tools read a config file with "r", and when it is missing they say so clearly with perror and fall back to defaults. Binary formats such as images, audio and database pages are handled with fread and fwrite in "rb" and "wb" mode.

Programs that must never lose data, such as text editors and databases, avoid overwriting a file in place. They write a new file first (for example notes.txt.tmp), confirm that fclose succeeded, and only then swap it in with rename(). If the power fails mid-write, the old file survives intact. Every one of those safety nets depends on checking return values.

Common mistakes

Common mistakes

1. Looping with while (!feof(f))

feof() only becomes true after a read has already failed. Write while (!feof(f)) { fgets(line, ...); printf("%s", line); } and the final fgets returns NULL while line still holds the previous text, so the last line is printed twice; a GCC 16 test on a file containing "a\nb\n" printed b twice. Make fgets's return value the loop condition instead.

2. Opening an existing file with "w"

"w" truncates the file the moment fopen is called, so the data is already gone even if the program crashes before writing anything. Use "a" for logs and history, and "r+" or the temporary-file technique when updating.

3. Forgetting fclose, or not checking it

Without fclose, buffered data may never reach the file, and opening files in a loop without closing them eventually hits the limit on open files. Only by checking fclose for EOF do you learn about write errors such as a full disk.

4. Writing binary data in text mode

On Windows, fwrite() through a "w" stream inserts a 0x0D byte before every 0x0A, which corrupts images and makes ints read back wrong. Linux shows no symptom, so the bug surfaces later as a cross-platform surprise. Always open binary data with "wb" and "rb".

Best practices

Best practices

  • Check every fopen for NULL and report it with perror(path), file name included.
  • Drive loops with the return value of fgets or fread, then check ferror() afterwards.
  • Close a file in the same function that opened it, and check the result.
  • Use a "b" mode for anything that is not text, and remove() temporary files when you are done.

Mini challenge

Mini challenge: a tiny log file

Write one function that appends a line to a log file and another that prints the file with line numbers, and make both cope with a missing file.

  • int append_line(const char *path, const char *text) uses "a" mode and returns 0, or -1 if fopen, fprintf or fclose fails
  • int print_numbered(const char *path) prints lines as "1: ..." and returns the line count, or -1 on error
  • main() deletes log-demo.txt first, appends started / processing / finished, prints the file, then deletes it again
  • Calling print_numbered() on the missing no-such-file.txt must report the -1
tiny_log.c
#include <stdio.h>
#include <string.h>

/* Appends text and a newline. Returns 0 on success, -1 on error. */
int append_line(const char *path, const char *text) {
    // TODO: open in append mode and check for NULL
    // TODO: write the text and a newline, remember if it failed
    // TODO: fclose and check it too
    return -1;
}

/* Prints each line with its number. Returns the count, or -1 on error. */
int print_numbered(const char *path) {
    // TODO: open for reading, check for NULL
    // TODO: fgets loop; strip the newline; print "n: line"
    // TODO: ferror check, fclose, return the count
    return -1;
}

int main(void) {
    // TODO: remove("log-demo.txt") first, because "a" keeps old lines
    // TODO: append three events, then print_numbered and the count
    // TODO: remove the file, then try print_numbered("no-such-file.txt")
    return 0;
}

Expected: The program prints: 1: started 2: processing 3: finished lines in file: 3 no-such-file.txt could not be opened

Show hint

Strip fgets' newline with line[strcspn(line, "\n")] = '\0';. In append_line(), still call fclose when fprintf fails, and only then return -1, or the file handle leaks.

Show solution
tiny_log.c
#include <stdio.h>
#include <string.h>

/* Appends text and a newline. Returns 0 on success, -1 on error. */
int append_line(const char *path, const char *text) {
    FILE *f = fopen(path, "a");
    if (f == NULL) {
        return -1;
    }
    int ok = fprintf(f, "%s\n", text) >= 0;
    if (fclose(f) == EOF) {
        ok = 0;
    }
    return ok ? 0 : -1;
}

/* Prints each line with its number. Returns the count, or -1 on error. */
int print_numbered(const char *path) {
    FILE *f = fopen(path, "r");
    if (f == NULL) {
        return -1;
    }
    char line[200];
    int n = 0;
    while (fgets(line, sizeof line, f) != NULL) {
        line[strcspn(line, "\n")] = '\0';
        printf("%d: %s\n", ++n, line);
    }
    int failed = ferror(f);
    fclose(f);
    return failed ? -1 : n;
}

int main(void) {
    const char *path = "log-demo.txt";
    remove(path);                         /* start fresh: "a" keeps old lines */

    const char *events[] = {"started", "processing", "finished"};
    for (int i = 0; i < 3; i++) {
        if (append_line(path, events[i]) != 0) {
            perror(path);
            return 1;
        }
    }
    int lines = print_numbered(path);
    if (lines < 0) {
        perror(path);
        return 1;
    }
    printf("lines in file: %d\n", lines);
    remove(path);

    if (print_numbered("no-such-file.txt") < 0) {
        printf("no-such-file.txt could not be opened\n");
    }
    return 0;
}

Quick quiz 1 / 3

You want each run to add new lines at the end of a log while keeping the old ones. Which mode do you use?

Quick quiz 2 / 3

What does while (!feof(f)) { fgets(line, sizeof line, f); printf("%s", line); } print for a file containing "a\nb\n"?

Quick quiz 3 / 3

On Windows, what bytes reach the disk when fputc('\n', f) writes to a file opened with "w"?

What to remember

  • fopen() can return NULL, so always check it and report the reason with perror(); relative paths start from the current working directory.
  • "w" erases a file on open and "a" appends; add "b" for anything that is not text.
  • Loop on fgets's return value and use ferror() to spot errors; never loop on while (!feof(f)).
  • Writes go to a buffer first, so always call fclose() and check whether it returned EOF.

GNU C compiler diagnostics — GNU Project

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

File I/O | Thuta Learning