Reading and writing text files
We'll next focus on reading and writing from human-readable text files.
C11 provides additional support above the operating systems's
system-calls
to provide more efficient buffering of I/O operations,
and treating text files as a sequence of lines (as strings).
We open a text file using C's fopen() function.
To this function we pass the name of the file we wish to open
(as a character array),
and describe how we wish to open, and later access, the file.
The returned value is a FILE pointer,
that we use in all subsequent operations with that file.
#include <stdio.h>
#define DICTIONARY "/usr/share/dict/words"
....
// ATTEMPT TO OPEN THE FILE FOR READ-ACCESS
FILE *dict = fopen(DICTIONARY, "r");
// CHECK IF ANYTHING WENT WRONG
if(dict == NULL) {
printf( "cannot open dictionary '%s'\n", DICTIONARY);
exit(EXIT_FAILURE);
}
// READ AND PROCESS THE CONTENTS OF THE FILE
....
// WHEN WE'RE FINISHED, CLOSE THE FILE
fclose(dict);
|
If fopen() returns the special value NULL,
it indicates that the file may not exist,
or that the operating system is not giving us permission to access it as
requested.
CITS2002 Systems Programming, Lecture 7, p3, 12th August 2024.
|