Lesson 25: Files — writing with fopen & fprintf
All our variables live in memory — and the moment the program ends, they vanish. Files solve this: data written to a file stays on disk even after the program closes. FILE *f = fopen("data.txt", "w"); opens a file for writing, and you MUST check that it didn't return NULL (bad path or missing permis
Memory is a whiteboard that gets erased every evening; a file is a notebook. What you wrote in the notebook waits for you tomorrow — but if you didn't close it properly (fclose), the last page might get lost.
- fopen
- Opens a file and returns a FILE *. If opening fails it returns NULL, so we always check.
- open mode ("w" / "a")
- "w" opens for writing and erases existing content; "a" appends at the end without erasing.
- fprintf
- Like printf but the output goes to a file: fprintf(f, "x=%d\n", x);.
- fputs
- Writes a plain string to a file, no formatting: fputs("hello\n", f);.
- fclose
- Flushes the buffer to disk and closes the file. Mandatory at the end — like free for memory.