364 Chapter 16 Input and Output Operations in C
If you take the preceding comments into account, the statements
#include <stdio.h>
FILE *inputFile;
inputFile = fopen ("data", "r");
have the effect of opening a file called datain read mode. (Write mode is specified by
the string "w", and append mode is specified by the string "a".) The fopencall returns
an identifier for the opened file that is assigned to the FILEpointer variable inputFile.
Subsequent testing of this variable against the defined value NULL, as in the following:
if ( inputFile == NULL )
printf ("*** data could not be opened.\n");
else
// read the data from the file
tells you whether the open was successful.
You should always check the result of an fopencall to make certain it succeeds.
Using a NULLpointer can produce unpredictable results.
Frequently, in the fopencall, the assignment of the returned FILEpointer variable
and the test against the NULLpointer are combined into a single statement, as follows:
if ( (inputFile = fopen ("data", "r")) == NULL )
printf ("*** data could not be opened.\n");
The fopenfunction also supports three other types of modes, called updatemodes ("r+",
"w+",and "a+"). All three update modes permit both reading and writing operations to
be performed on a file. Read update ("r+") opens an existing file for both reading and
writing.Write update ("w+") is like write mode (if the file already exists, the contents are
destroyed; if one doesn’t exist, it’s created), but once again both reading and writing are
permitted. Append update ("a+") opens an existing file or creates a new one if one
doesn’t exist. Read operations can occur anywhere in the file, but write operations can
only add data to the end.
Under operating systems such as Windows, which distinguish text files from binary
files, a bmust be added to the end of the mode string to read or write a binary file. If
you forget to do this, you will get strange results, even though your program will still
run.This is because on these systems, carriage return/line feed character pairs are con-
verted to return characters when they are read from or written to text files.
Furthermore, on input, a file that contains a Ctrl+Z character causes an end-of-file con-
dition if the file was not opened as a binary file. So,
inputFile = fopen ("data", "rb");
opens the binary file datafor reading.