File I/O
Programs become useful when they can read data in and write results out: config files, logs, CSV exports, images. C's standard library handles files through a FILE * "stream", the same kind of object as the screen (stdout) and keyboard (stdin) you've already used.
Writing a text file
#include <stdio.h>
int main(void) {
FILE *f = fopen("report.txt", "w");
if (f == NULL) {
perror("report.txt");
return 1;
}
fprintf(f, "Sales report\n");
fprintf(f, "%-10s %5s\n", "product", "units");
fprintf(f, "%-10s %5d\n", "keyboard", 12);
fprintf(f, "%-10s %5d\n", "mouse", 40);
fputs("end of report\n", f);
if (fclose(f) != 0) {
perror("closing report.txt");
return 1;
}
printf("report written\n");
return 0;
}report written
cat report.txtSales report product units keyboard 12 mouse 40 end of report
The three steps are always the same: open with fopen, read or write, close with fclose.
| Mode | Opens for | If the file exists | If it doesn't |
|---|---|---|---|
"r" |
Reading | Read from the start | Fails (NULL) |
"w" |
Writing | Erased | Created |
"a" |
Appending | Writes go to the end | Created |
"r+" |
Reading and writing | Kept | Fails |
"wx" |
Writing, exclusive (C11) | Fails (safe "create new") | Created |
Add b ("rb", "wb") for binary files. On Linux and macOS it changes nothing, but on Windows it stops newline conversion, so use it for anything that isn't text.
Errors: NULL, errno and perror
fopen returns NULL on failure and sets errno to a code saying why. perror prints your message plus the reason:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(void) {
FILE *f = fopen("/no/such/folder/data.txt", "r");
if (!f) {
perror("open data.txt");
printf("errno = %d (%s)\n", errno, strerror(errno));
}
f = fopen("/", "w");
if (!f) perror("open / for writing");
return 0;
}open data.txt: No such file or directory errno = 2 (No such file or directory) open / for writing: Is a directory
Always check fopen. A missing file, a wrong path or missing permissions are everyday events, and using a NULL FILE * crashes the program.
Reading line by line
fgets reads one line (up to a size limit) at a time. It returns NULL at the end of the file:
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = fopen("report.txt", "r");
if (!f) { perror("report.txt"); return 1; }
char line[256];
int n = 0;
while (fgets(line, sizeof line, f) != NULL) {
line[strcspn(line, "\n")] = '\0';
printf("%2d: %s\n", ++n, line);
}
if (ferror(f)) perror("reading report.txt");
fclose(f);
printf("%d lines\n", n);
return 0;
}1: Sales report 2: product units 3: keyboard 12 4: mouse 40 5: end of report 5 lines
For lines of any length, POSIX systems (Linux, macOS) have getline, which grows its buffer with malloc as needed. With a strict -std=c23, POSIX functions are hidden unless you ask for them with _POSIX_C_SOURCE before the first #include (or compile with -std=gnu23):
#define _POSIX_C_SOURCE 200809L // ask for POSIX functions like getline
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = fopen("report.txt", "r");
if (!f) return 1;
char *line = NULL;
size_t cap = 0;
ssize_t len;
size_t longest = 0;
while ((len = getline(&line, &cap, f)) != -1) {
if ((size_t)len > longest) longest = (size_t)len;
}
free(line);
fclose(f);
printf("longest line: %zu characters including the newline\n", longest);
return 0;
}longest line: 17 characters including the newline
Parsing a CSV file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
FILE *out = fopen("sales.csv", "w");
if (!out) return 1;
fputs("region,product,units,price\n"
"north,keyboard,3,49.50\n"
"south,mouse,10,19.99\n"
"north,monitor,2,229.00\n"
"east,keyboard,oops,49.50\n", out);
fclose(out);
FILE *f = fopen("sales.csv", "r");
if (!f) { perror("sales.csv"); return 1; }
char line[256];
fgets(line, sizeof line, f); // skip the header
double revenue = 0;
int lineno = 1;
while (fgets(line, sizeof line, f)) {
lineno++;
char region[32], product[32];
int units;
double price;
if (sscanf(line, "%31[^,],%31[^,],%d,%lf", region, product, &units, &price) != 4) {
fprintf(stderr, "line %d: can't parse, skipped\n", lineno);
continue;
}
revenue += units * price;
printf("%-6s %-9s %3d x %7.2f\n", region, product, units, price);
}
fclose(f);
printf("revenue: %.2f\n", revenue);
return 0;
}north keyboard 3 x 49.50 south mouse 10 x 19.99 north monitor 2 x 229.00 line 5: can't parse, skipped revenue: 806.40
sscanf parses a string the way scanf parses input. %31[^,] means "up to 31 characters that aren't a comma", which keeps it inside the 32-byte buffer. Checking its return value catches bad lines. (Real CSV can contain quoted commas; for that, use a proper CSV library.)
Binary files: fread and fwrite
Binary files store raw bytes, which is faster and smaller than text. fwrite writes a block of memory; fread reads it back:
#include <stdio.h>
#include <stdint.h>
typedef struct {
uint32_t id;
int32_t temperature_milli; // 21.5 °C stored as 21500
} Reading;
int main(void) {
Reading out[] = {{1, 21500}, {2, 22125}, {3, 19875}};
FILE *f = fopen("readings.bin", "wb");
if (!f) return 1;
size_t written = fwrite(out, sizeof out[0], 3, f);
fclose(f);
printf("wrote %zu readings\n", written);
Reading in[3];
f = fopen("readings.bin", "rb");
if (!f) return 1;
size_t got = fread(in, sizeof in[0], 3, f);
fclose(f);
for (size_t i = 0; i < got; i++) {
printf("reading %u: %.3f °C\n", in[i].id, in[i].temperature_milli / 1000.0);
}
return 0;
}wrote 3 readings reading 1: 21.500 °C reading 2: 22.125 °C reading 3: 19.875 °C
ls -l readings.bin
od -An -tx1 readings.bin24 bytes 01 00 00 00 fc 53 00 00 02 00 00 00 6d 56 00 00 03 00 00 00 a3 4d 00 00
Three readings of 8 bytes each = 24 bytes. od shows the raw bytes: 01 00 00 00 is the id 1 stored little-endian (lowest byte first), as on all x86 and ARM machines. Writing whole structs like this is fine for a program reading its own files on one machine. For files shared between systems, write each field in a fixed byte order, and use fixed-width types (uint32_t), as here.
fread and fwrite return how many items they handled. Fewer than asked means the end of the file or an error; tell them apart with feof(f) and ferror(f).
Moving around: fseek and ftell
#include <stdio.h>
int main(void) {
FILE *f = fopen("report.txt", "rb");
if (!f) return 1;
fseek(f, 0, SEEK_END);
long size = ftell(f);
printf("report.txt is %ld bytes\n", size);
fseek(f, -14, SEEK_END); // 14 bytes before the end
char tail[32] = {0};
fread(tail, 1, sizeof tail - 1, f);
printf("last 14 bytes: %s", tail);
rewind(f); // back to the start
printf("first char: %c\n", fgetc(f));
fclose(f);
return 0;
}report.txt is 78 bytes last 14 bytes: end of report first char: S
stdin, stdout and stderr
The three standard streams are FILE *s too, so every function above works with them. Errors and progress messages belong on stderr, so they don't get mixed into output someone is saving:
#include <stdio.h>
// Count lines, words and characters from stdin (a tiny version of `wc`).
int main(void) {
long lines = 0, words = 0, chars = 0;
int c, in_word = 0;
while ((c = getchar()) != EOF) {
chars++;
if (c == '\n') lines++;
if (c == ' ' || c == '\n' || c == '\t') in_word = 0;
else if (!in_word) { in_word = 1; words++; }
}
fprintf(stderr, "(finished reading)\n");
printf("%ld %ld %ld\n", lines, words, chars);
return 0;
}gcc -std=c23 -Wall -Wextra -o mywc wc.c
./mywc < report.txt
./mywc < report.txt 2>/dev/null > counts.txt
cat counts.txt
wc report.txt(finished reading) 5 11 78 5 11 78 5 11 78 report.txt
getchar() returns an int, not a char: it needs one extra value, EOF, for "no more input". Storing it in a char is a classic bug. The program reads from stdin, so the shell can feed it any file or pipe, which is the Unix way of building tools.
Buffering
stdio collects output in a buffer and writes it in big chunks, which is much faster. The catch: if the program crashes, buffered output is lost. fflush(f) writes the buffer out now; stdout is flushed at every newline when it's a terminal, but not when it's redirected to a file or pipe. stderr is never buffered, which is another reason to send error messages there.
Practice
- Write
copy SRC DESTthat copies a file in 4 KB chunks withfread/fwrite, reporting errors withperror. - Count how often each letter a–z appears in a text file.
- Append a timestamped line to
app.logevery time your program runs (look uptimeandstrftime). - Read
sales.csvand write a new file containing only thenorthrows.
1.What does fopen("data.txt", "w") do if data.txt already exists?
2.How do you find out why fopen returned NULL?
3.Why does getchar() return an int instead of a char?
4.Which function reads a whole line safely into a buffer?