C/C++ Arena

File I/O in C

Open, read, write and close files in C with fopen, fprintf, fgets and fclose, and handle errors.

fopen(name, mode) opens a file and returns a FILE *, or NULL if it failed (always check). Common modes are "r" (read), "w" (write, replacing the file) and "a" (append).

Write with fprintf or fputs, read lines with fgets, and always fclose when you're done so buffered data is written out.

fgets(buf, sizeof buf, f) reads one line (keeping the \n) and returns NULL at the end of the file, which makes it the standard loop condition.

Example

#include <stdio.h>

int main(void) {
    FILE *out = fopen("notes.txt", "w");
    if (!out) return 1;
    fprintf(out, "line one\nline two\n");
    fclose(out);

    FILE *in = fopen("notes.txt", "r");
    if (!in) return 1;
    char line[64];
    int count = 0;
    while (fgets(line, sizeof line, in)) count++;
    fclose(in);
    printf("%d lines\n", count);
    return 0;
}

Output:

2 lines

Practice it