Programming in C

(Barry) #1

368 Chapter 16 Input and Output Operations in C


have the effect of displaying the message “Ran out of data” at the terminal if an end-of-
file condition exists on the file identified by inFile.
Remember,feoftells you that an attempt has been made to read past the end of the
file, which is not the same as telling you that you just read the last data item from a file.
You have to read one past the last data item for feofto return nonzero.

The fprintfand fscanfFunctions


The functionsfprintfand fscanfare provided to perform the analogous operations of
the printfand scanffunctions on a file.These functions take an additional argument,
which is the FILEpointer that identifies the file to which the data is to be written or
from which the data is to be read. So, to write the character string "Programming in C
is fun.\n"into the file identified by outFile,you can write the following statement:
fprintf (outFile, "Programming in C is fun.\n");
Similarly, to read in the next floating-point value from the file identified by inFileinto
the variable fv, the statement
fscanf (inFile, "%f", &fv);
can be used. As with scanf,fscanfreturns the number of arguments that are successful-
ly read and assigned or the value EOF, if the end of the file is reached before any of the
conversion specifications have been processed.

The fgetsand fputsFunctions


For reading and writing entire lines of data from and to a file, the fputsand fgets
functions can be used.The fgetsfunction is called as follows:
fgets (buffer, n, filePtr);
bufferis a pointer to a character array where the line that is read in will be stored;nis
an integer value that represents the maximum number of characters to be stored into
buffer;and filePtridentifies the file from which the line is to be read.
The fgetsfunction reads characters from the specified file until a newline character
has been read (which willget stored in the buffer) or until n-1characters have been read,
whichever occurs first.The function automatically places a null character after the last
character in buffer. It returns the value of buffer(the first argument) if the read is suc-
cessful, and the value NULLif an error occurs on the read or if an attempt is made to read
past the end of the file.
fgetscan be combined with sscanf(see Appendix B) to perform line-oriented
reading in a more orderly and controlled fashion than by using scanfalone.
The fputsfunction writes a line of characters to a specified file.The function is
called as follows:
fputs (buffer, filePtr);
Free download pdf