File I/O
Challenge Gallery
Quick Reference
File modes:
| Mode | Meaning | Creates? | Truncates? |
|---|---|---|---|
"r" |
Read only | No (must exist) | No |
"w" |
Write (create/overwrite) | Yes | Yes |
"a" |
Append | Yes | No |
Read/write functions:
| Function | Purpose | Check return |
|---|---|---|
fprintf(fp, fmt, ...) |
Write formatted to file | — |
fscanf(fp, fmt, ...) |
Read formatted from file | == expected_count |
fgets(buf, size, fp) |
Read one line safely | != NULL |
fputs(str, fp) |
Write string to file | — |
Standard pattern:
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) { perror("data.txt"); return 1; }
char line[256];
while (fgets(line, sizeof(line), fp) != NULL) {
line[strcspn(line, "\n")] = '\0';
// process line
}
fclose(fp);
Shell ↔ C mapping:
| Shell | C equivalent |
|---|---|
printf(...) |
fprintf(stdout, ...) |
./prog > file |
fprintf(fp, ...) |
scanf(...) |
fscanf(stdin, ...) |
./prog 2> err |
fprintf(stderr, ...) |
Common Pitfalls
while (!feof(fp))— Processes garbage on last iteration. Usewhile (fscanf(...) == n)orwhile (fgets(...) != NULL)."w"truncates — Opens and erases. Use"a"for append.- Not checking fopen — Returns NULL on failure. Dereferencing NULL FILE * crashes.
- Forgetting fclose — Buffered data may not be written. Always close.
- fgets newline — Includes
\n. Strip withstrcspn. - Mixing fgets and fscanf — fscanf leaves
\nin buffer. Clear withwhile(fgetc(fp)!='\n'){}or use fgets consistently.