CC Explainer
C · 3 · Structs, Unions & I/O13 / 35 · 37%

File I/O

fopen / fread / fwrite / fclose — the stdio buffered stream API.

shortcuts: ← prev · → next · M mark
1

Text Files

Open in text mode, read/write line by line.

Example
example
FILE *f = fopen("log.txt", "w");
if (!f) { perror("open"); return 1; }
fprintf(f, "hello %d\n", 42);
fclose(f);
2

Read a File

fgets reads one line, up to size-1 chars, keeping the newline.

Example
example
char buf[256];
FILE *f = fopen("log.txt", "r");
while (fgets(buf, sizeof buf, f)) {
    fputs(buf, stdout);
}
fclose(f);
3

Binary I/O

Read raw structs in one shot with fread/fwrite.

Example
example
Point p = {3, 4};
FILE *f = fopen("p.bin", "wb");
fwrite(&p, sizeof p, 1, f);
fclose(f);
WATCH OUT
Binary format is not portable across CPUs (endianness, padding).
4

errno & perror

Every stdio call sets errno on failure. perror prints a human message.

Example
example
#include <errno.h>

FILE *f = fopen("/no/such/file", "r");
if (!f) {
    perror("fopen");     // e.g. "fopen: No such file or directory"
    printf("errno=%d\n", errno);
}