Learn C
#include "ioformatting/file_io.h"

File I/O: fopen, fprintf, fscanf in C

#concept

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.

#how it works
1

Open with the right mode

fopen("out.txt", "w") truncates existing content; "a" preserves and appends; "r" fails (NULL) when missing.

2

NULL means it failed

if (!fp) { perror("open"); return 1; } — missing files and denied permissions surface here, nowhere else.

3

Same functions, FILE* target

fprintf(fp, ...), fscanf(fp, ...), fgets(buf, n, fp) mirror console I/O with the stream as an extra argument.

4

Close to flush

fclose(fp) writes buffered data out and frees the stream — skipped closes lose trailing output.

#example
#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;
}
Output
remember this
1fopen for writing truncates/creates note.txt; the NULL check guards permission failures.
2fprintf formats into the file exactly like printf; fclose flushes it to disk.
3Reopening for reading plus fgets pulls the line back — printf("%s") adds no extra newline since the line keeps its own.
#use cases
Saving/loading program data, logs, and configs as text files
Appending with "a" mode for logs that must survive restarts
Checking every fopen before use — the #1 file-I/O crash source
Binary modes ("rb"/"wb") for exact-byte formats

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.