Reading a File Line by Line
On the previous page we learned about some functions to read from a file. Let's write some more code using one of them, fgets.
The fgets function accepts a buffer (that is, a char array) of some size, the size, and the file. It will keep reading characters from the file into the array and will stop either when it reads '\n', or when the file ends, or when the buffer is about to end. It will always add a zero character to terminate the string it filled with characters. It will return the buffer, unless it was unable to read any characters, in which case it will return a null pointer NULL.
Let's imagine we have the following code:
char buf[10];
char *result;
FILE *f;
f = fopen("input.txt", "r"); /* assuming it exists, need to check that f is not NULL */
result = fgets(buf, 10, f);
Assuming that the file exists (otherwise fopen would return NULL), the fgets call can do the following:
- If the file is empty, it won't read anything, and will return
NULL. - If the file is not empty and the first line (that is, all the characters before the first
\n) is 9 characters or less, it will write those characters and'\n'to the buffer, and then write a zero character. For example, if the first line of the file is `"abcde\n", the buffer will contain these 6 characters, and then zero. - If the file is not empty, but the first line is longer than 9 characters, it will write 9 characters to the buffer, and write a zero character after them. The buffer won't have
'\n'before the zero character.
Note that it will read 9, not 10, characters, because it needs to leave one position for the zero character at the end of the string.
If we call fgets one more, it will keep reading characters from the file, starting from the next character. It allows us to use a simple while loop to call fgets until it returns NULL, reading the whole file:
char buf[100];
while (fgets(buf, 100, f)) { /* read line by line */
...
}
Ready to try? The file input.txt has several lines of text in it. Read it line by line using fgets, and print everything back using printf.
#include <stdio.h>
int main() {
/* TODO: fopen "input.txt" for reading, then fgets in a loop and printf */
return 0;
}
I hope it worked! On the next page we'll learn about the special file stdin. Stay tuned!