student@ubuntu:~$
Topic Week 5 2 min overview

Files

FILE*, fopen, fread/fwrite, fscanf/fprintf, and why stderr exists

In a nutshell

In Java you used Scanner, BufferedReader, or Files.readAllLines. In C you use FILE *, a handle that fopen returns. You open a file with a mode (“r” read, “w” write, “a” append, “rb” binary read, and so on), read or write through the handle with fread/fwrite (binary) or fscanf/fprintf (formatted), and close it with fclose. Every mechanic you learned about printf and scanf applies: fprintf is printf to a file, fscanf is scanf from a file. stdin, stdout, and stderr are already-open FILE * handles the OS gives you.

Why it matters

Every non-trivial program reads or writes files. Log-processing tools, networking code (sockets look a lot like files on Unix), configuration parsers, serialization. Lab 7 and several later labs will hand you an input file or require you to produce an output file. Checking return values religiously (fopen returns NULL on failure, fread tells you how many elements it actually read) is also a microcosm of all Unix-style system call discipline.

Key takeaways

  • FILE * is a pointer to a libc-owned struct that tracks the file’s state.
  • fopen(path, mode) returns NULL on failure. Always check.
  • Modes: "r" read, "w" write-truncate, "a" append, "r+" read/write, "rb"/"wb" binary. Forgetting the b on Windows corrupts binary data; on Linux it is harmless but a good habit.
  • fread(buf, size, count, fp) reads up to count elements of size bytes each. Returns the count actually read. On short reads, check feof(fp) vs ferror(fp).
  • fwrite(buf, size, count, fp) is the symmetric write. Returns the count actually written.
  • fscanf and fprintf work like scanf and printf but on a file handle. All the format-specifier rules still apply.
  • fclose(fp) always. Matching open/close is as important as matching malloc/free.
  • stderr for diagnostics. fprintf(stderr, "...") keeps error messages out of pipelines that consume stdout. Every command-line tool should follow this convention.

Lessons in this topic

Lesson What it covers
File I/O: FILE *, fopen, fread Opening, reading, writing, closing; the standard streams; error checking

Planned for this week (coming):

  • fscanf vs fgets for line-oriented input
  • fprintf(stderr, ...) as the diagnostic convention
  • The feof / ferror / return-value protocol

Practice and deep dives

Practice this topic: File I/O drill, or browse the practice gallery.

What comes next

Three-File Format — the organizational pattern that keeps multi-file C programs maintainable. Every lab from Lab 6 onward uses it, and now that you have functions, pointers, and allocations to share across files, you need the headers and extern rules that make sharing safe.