Nearby lessons
71 of 72C - Reading from a File
Reading from a file allows a C program to use information saved earlier. Learn how to read a line with fgets() and how to stop when there is no more data to read.
1. Read a File Using fgets()
The fgets() function reads text from a file into a character array. It can read spaces and stops after a newline, when the buffer is full, or at the end of the file.
2. Read Formatted Data Using fscanf()
fscanf() is useful when the file contains data in a known format, such as a name followed by a number. The loop below continues while both values are read successfully.
3. Understanding EOF
EOF is a special value used by input functions to indicate that no more input can be read, or that an input error occurred. For beginners, prefer checking the return value of fgets() or the number of values returned by fscanf() instead of using feof() as the loop condition.
- Use r mode to read an existing file.
- fgets() can read a line including spaces.
- A loop using fgets() stops when no more line can be read.
- Always close the file after reading.