Loading...

C essentialsFiles & System

File I/O: fopen, fread, fwrite & fclose

12 min lesson

Next
  • File I/O lets your program read from and write to files on disk using functions like fopen, fread, fwrite and fclose.
  • It matters because real programs need to save data between runs, read configuration, process logs, or handle binary formats.
  • Think of a file as a notebook on a shelf. fopen opens the notebook, fread reads pages, fwrite writes pages, and fclose puts it back on the shelf.
  • fopen(path, mode) returns a FILE * handle, or NULL on failure. Modes include "r" (read), "w" (write, truncates), and "a" (append).
  • fread(buffer, size, count, f) reads count items of size bytes into buffer and returns how many were read.
  • fwrite(buffer, size, count, f) writes count items of size bytes from buffer to the file.
  • fclose(f) flushes and closes the file; forgetting it can lose data and leak file handles.
  • The computer maintains a buffer for each open file, so writes may not hit disk until you flush or close.
  • The syntax is: FILE *f = fopen("data.bin", "wb"); then fwrite(buf, sizeof buf[0], n, f); then fclose(f);.
  • A realistic use: saving a small array of records to disk and reading it back on the next run.
  • A surprising detail: text mode "r" and "w" translate line endings on some systems, while "rb" and "wb" read and write raw bytes.
  • The example program writes three integers to a binary file, closes it, reopens it, reads them back and prints them.
Keep in mind
  • Always check that fopen returned a non-NULL FILE * before using it.
  • Use "rb" and "wb" for binary data and "r" and "w" for text.
  • Check the return value of fread and fwrite to know how many items were processed.
  • Always fclose every file you open, even on error paths.
  • File I/O makes your programs remember data. Great milestone!
main.c
#include <stdio.h>

int main(void) {
    // Data to write to the file
    int values[3] = {11, 22, 33};
    const char *path = "data.bin";

    // Open the file for binary writing
    FILE *out = fopen(path, "wb");
    // Check that the file opened successfully
    if (out == NULL) {
        perror("fopen for write");
        return 1;
    }
    // Write all three ints in one call; check the count
    size_t written = fwrite(values, sizeof values[0], 3, out);
    if (written != 3) {
        perror("fwrite");
        fclose(out);
        return 1;
    }
    // Close the file so the data is flushed to disk
    fclose(out);

    // Open the same file for binary reading
    FILE *in = fopen(path, "rb");
    if (in == NULL) {
        perror("fopen for read");
        return 1;
    }
    // A buffer to hold the data we read back
    int buffer[3] = {0};
    // Read three ints back into the buffer
    size_t readCount = fread(buffer, sizeof buffer[0], 3, in);
    // Close the input file
    fclose(in);

    // Print how many were read and their values
    printf("Read %zu values\n", readCount);
    for (int i = 0; i < 3; i++) {
        printf("buffer[%d] = %d\n", i, buffer[i]);
    }

    return 0;
}

What happens: Read 3 values buffer[0] = 11 buffer[1] = 22 buffer[2] = 33

Breaking it down

fopen for writing

fopen(path, "wb")

Opens the file for binary writing, creating it or truncating it if it exists. Returns NULL on failure.

fwrite call

fwrite(values, sizeof values[0], 3, out)

Writes 3 ints from values to the file. It returns how many items were written, which should be 3.

fclose

fclose(out);

Flushes buffered data to disk and releases the file handle. Without it, data may be lost and handles leak.

fopen for reading

fopen(path, "rb")

Opens the same file for binary reading. The file must exist, or fopen returns NULL.

fread call

fread(buffer, sizeof buffer[0], 3, in)

Reads up to 3 ints into buffer. It returns how many were actually read, which may be fewer at end of file.

File modes and functions

ItemMeaningExample
"r"Read textfopen("a.txt", "r")
"w"Write text, truncatefopen("a.txt", "w")
"a"Append textfopen("a.txt", "a")
"rb"Read binaryfopen("a.bin", "rb")
freadRead itemsfread(buf, 4, 3, f)
fwriteWrite itemsfwrite(buf, 4, 3, f)
fcloseClose and flushfclose(f)

A helpful analogy

A file is like a notebook on a shelf. fopen takes the notebook down and opens it in the mode you choose. fread reads pages into your hands, fwrite writes pages from your notes, and fclose puts the notebook back so others can use it. The shelf (disk) only gets the new pages when you flush or close.

Nesting rules

  • 1.Check that fopen returned non-NULL before using the FILE *.
  • 2.Use binary modes "rb" and "wb" for data you read and write with fread and fwrite.
  • 3.Check the count returned by fread and fwrite against what you expected.
  • 4.Always fclose every FILE * you open, including on error paths.

Common mistakes

Using the FILE * without checking fopen

Avoid

FILE *f = fopen("x", "r"); fgetc(f); // crash if NULL

Use instead

if (!(f = fopen("x", "r"))) { perror("fopen"); return 1; }

fopen returns NULL on failure, and passing NULL to file functions is undefined behavior and usually crashes.

Forgetting fclose

Avoid

fwrite(buf, 1, n, f); // no fclose

Use instead

fwrite(buf, 1, n, f); fclose(f);

Buffered writes may not reach disk until close. Missing fclose can lose data and leak a file handle.

Ignoring the return value of fread

Avoid

fread(buf, 4, 10, f); // maybe fewer read

Use instead

size_t n = fread(buf, 4, 10, f); // use n

fread may read fewer items at end of file. Using unread buffer slots reads uninitialized data.

Quick tips

  • •Open files in the narrowest mode you need: read-only if you will not write.
  • •Use fwrite and fread with sizeof to keep sizes correct as types change.
  • •After writing, close and reopen the file to confirm the data is on disk.
  • •Try changing the values in the array and rerun to see the file change.
  • •Check the return value of fclose for write errors on some systems.
Previous
Next