11.1 File Basics: fopen(), Modes, and fclose()
FILE *fp = fopen("name.txt", "mode") opens a file and returns a pointer used for all subsequent operations on it (or NULL if it fails, e.g. file not found). Common modes: "r" read, "w" write (creates/overwrites), "a" append, "r+" read & write. fclose(fp) must be called when finished — it flushes any buffered data to disk and releases the file handle.
11.2 Reading and Writing Functions
fprintf/fscanf work like printf/scanf but target a file instead of the console. fputs/fgets write and read whole lines of text. fread/fwrite handle raw binary data in fixed-size blocks — used for structs, images, or any non-text data — and are typically paired with sizeof() to specify block size.
| Function | Use |
|---|---|
fprintf(fp, fmt, ...) | Write formatted text to a file |
fscanf(fp, fmt, ...) | Read formatted text from a file |
fgets(buf, n, fp) | Read up to n-1 characters or one line |
fwrite(ptr,size,n,fp) | Write raw binary data |
fread(ptr,size,n,fp) | Read raw binary data |