Reading a text file, one line at a time
Having opened the file (for read access),
we now wish to read it in -
one line at a time.
We generally don't need to store each line of text;
we just check or use it as we traverse the file:
The text data in the file is (unsurprisingly) also stored as a sequence
of characters.
We can use C's character arrays to store each line as we read it:
#include <stdio.h>
....
FILE *dict;
char line[BUFSIZ];
dict = fopen( ..... );
....
// READ EACH LINE FROM THE FILE,
// CHECKING FOR END-OF-FILE OR AN ERROR
while( fgets(line, sizeof line, dict) != NULL ) {
....
.... // process this line
....
}
// AT END-OF-FILE (OR AN ERROR), CLOSE THE FILE
fclose(dict);
|
|
Of note in this code:
- we pass to fgets() our character array,
into which each line will be read.
- we indicate the maximum size of our array,
so that fgets() doesn't try to read in too much.
- We use the sizeof operator to indicate the
maximum size of our character array.
Using sizeof here, rather than just repeating
the value BUFSIZ,
means that we can change the size of line at any time,
by only changing the size at its definition.
- We pass our file pointer, dict,
to our file-based functions to indicate which file to read or write.
It's possible to have many files open at once.
- The fgets() functions returns the constant NULL
when it "fails".
When reading files, this indicates that the end-of-file has
been reached, or some error detected (e.g. USB key removed!).
- Assuming that we've reached end-of-file,
and that we only need to read the file once,
we close the file pointer
(and just assume that the closing has succeeded).
|
CITS2002 Systems Programming, Lecture 7, p5, 12th August 2024.
|