File I/O: fopen, fprintf, fscanf in C
Files are FILE* streams opened with fopen(path, mode): "r" read, "w" write (truncates!), "a" append, plus "b" for binary and "+" for update. fprintf/fscanf/fgets/fputs work on them exactly like their console twins, and fclose flushes and releases — always check fopen's NULL return before touching the stream.
Text vs binary matters on Windows (newline translation); "rb"/"wb" disables it for exact bytes. Files also buffer: data you wrote may sit in memory until fflush, fclose, or exit — missing output usually means missing close, not missing writes.
Open with the right mode
fopen("out.txt", "w") truncates existing content; "a" preserves and appends; "r" fails (NULL) when missing.
NULL means it failed
if (!fp) { perror("open"); return 1; } — missing files and denied permissions surface here, nowhere else.
Same functions, FILE* target
fprintf(fp, ...), fscanf(fp, ...), fgets(buf, n, fp) mirror console I/O with the stream as an extra argument.
Close to flush
fclose(fp) writes buffered data out and frees the stream — skipped closes lose trailing output.
#include <stdio.h> int main(void) { FILE *out = fopen("note.txt", "w"); if (!out) { perror("open"); return 1; } fprintf(out, "remember %s\n", "this"); fclose(out); FILE *in = fopen("note.txt", "r"); char line[64]; if (in && fgets(line, sizeof line, in)) printf("%s", line); if (in) fclose(in); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.