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)returnsNULLon failure. Always check.- Modes:
"r"read,"w"write-truncate,"a"append,"r+"read/write,"rb"/"wb"binary. Forgetting thebon Windows corrupts binary data; on Linux it is harmless but a good habit. fread(buf, size, count, fp)reads up tocountelements ofsizebytes each. Returns the count actually read. On short reads, checkfeof(fp)vsferror(fp).fwrite(buf, size, count, fp)is the symmetric write. Returns the count actually written.fscanfandfprintfwork likescanfandprintfbut on a file handle. All the format-specifier rules still apply.fclose(fp)always. Matching open/close is as important as matchingmalloc/free.stderrfor diagnostics.fprintf(stderr, "...")keeps error messages out of pipelines that consumestdout. 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):
fscanfvsfgetsfor line-oriented inputfprintf(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.