Programming in C

(Barry) #1
Special Functions for Working with Files 365

The getcand putcFunctions


The function getcenables you to read in a single character from a file.This function
behaves identically to the getcharfunction described previously.The only difference is
that getctakes an argument: a FILEpointer that identifies the file from which the char-
acter is to be read. So, if fopenis called as shown previously, then subsequent execution
of the statement


c = getc (inputFile);


has the effect of reading a single character from the file data. Subsequent characters can
be read from the file simply by making additional calls to the getcfunction.
The getcfunction returns the value EOFwhen the end of file is reached, and as with
the getcharfunction, the value returned by getcshould be stored in a variable of
type int.
As you might have guessed, the putcfunction is equivalent to the putcharfunction,
only it takes two arguments instead of one.The first argument to putcis the character
that is to be written into the file.The second argument is the FILEpointer. So the call


putc ('\n', outputFile);


writes a newline character into the file identified by the FILEpointer outputFile.Of
course, the identified file must have been previously opened in either write or append
mode (or in any of the update modes) for this call to succeed.


The fcloseFunction


One operation that you can perform on a file, which must be mentioned, is that of clos-
ing the file.The fclosefunction, in a sense, does the opposite of what the fopendoes:
It tells the system that you no longer need to access the file.When a file is closed, the
system performs some necessary housekeeping chores (such as writing all the data that it
might be keeping in a buffer in memory to the file) and then dissociates the particular
file identifier from the file. After a file has been closed, it can no longer be read from or
written to unless it is reopened.
When you have completed your operations on a file, it is a good habit to close the
file.When a program terminates normally, the system automatically closes any open files
for you. It is generally better programming practice to close a file as soon as you are
done with it.This can be beneficial if your program has to deal with a large number of
files, as there are practical limits on the number of files that can be kept simultaneously
open by a program.Your system might have various limits on the number of files that
you can have open simultaneously.This might only be an issue if you are working with
multiple files in your program.
By the way, the argument to the fclosefunction is the FILEpointer of the file to be
closed. So, the call


fclose (inputFile);


closes the file associated with the FILEpointer inputFile.

Free download pdf