student@ubuntu:~$
c 3/5 30 XP

File I/O

0%

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. Use while (fscanf(...) == n) or while (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 with strcspn.
  • Mixing fgets and fscanf — fscanf leaves \n in buffer. Clear with while(fgetc(fp)!='\n'){} or use fgets consistently.

Unlocks

Complete this skill to see what it unlocks.