Lesson 26: Reading files & capstone project
Last lesson we wrote to files — now we learn to read them back. fopen("data.txt", "r") opens for reading, fgets(line, sizeof line, f) reads line by line in a while loop and returns NULL at end of file, and fscanf parses lines into values: while (fscanf(f, "%19s %d", name, &grade) == 2). Then — the c
Writing to a file is like dictating a letter; reading is opening the envelope and going line by line until the pages run out (NULL). And the capstone? Like the final dinner of a cooking course — every technique you learned shows up on one plate.
- read mode "r"
- fopen("data.txt", "r") opens an existing file for reading. If the file doesn't exist — returns NULL.
- fgets
- Reads one line into a char array: fgets(line, sizeof line, f). At end of file it returns NULL.
- fscanf
- Like scanf but from a file: parses text into values and returns how many values were read successfully.
- end of file (EOF)
- The point after the last character. There fgets returns NULL, and fscanf stops returning the full count.
- capstone project
- One program combining the whole course: a struct, a dynamic array, saving to a file, loading, free and fclose.