Special Functions for Working with Files 363
Special Functions for Working with Files
It is very likely that many of the programs you will develop will be able to perform all
their I/O operations using just the getchar,putchar,scanf,and printffunctions and
the notion of I/O redirection. However, situations do arise when you need more flexi-
bility to work with files. For example, you might need to read data from two or more
different files or to write output results into several different files.To handle these situa-
tions, special functions have been designed expressly for working with files. Several of
these functions are described in the following sections.
The fopenFunction
Before you can begin to do any I/O operations on a file, the file must first be opened.To
open a file, you must specify the name of the file.The system then checks to make cer-
tain that this file actually exists and, in certain instances, creates the file for you if it does
not.When a file is opened, you must also specify to the system the type of I/O opera-
tions that you intend to perform with the file. If the file is to be used to read in data,
you normally open the file in read mode. If you want to write data into the file, you open
the file in write mode. Finally, if you want to append information to the end of a file that
already contains some data, you open the file in append mode. In the latter two cases,
write and append mode, if the specified file does not exist on the system, the system cre-
ates the file for you. In the case of read mode, if the file does not exist, an error occurs.
Because a program can have many different files open at the same time, you need a
way to identify a particular file in your program when you want to perform some I/O
operation on the file.This is done by means of a file pointer.
The function called fopenin the standard library serves the function of opening a file
on the system and of returning a unique file pointer with which to subsequently identify
the file.The function takes two arguments:The first is a character string specifying the
name of the file to be opened; the second is also a character string that indicates the
mode in which the file is to be opened.The function returns a file pointer that is used
by other library functions to identify the particular file.
If the file cannot be opened for some reason, the function returns the value NULL,
which is defined inside the header file <stdio.h>.^3 Also defined in this file is the defini-
tion of a type called FILE.To store the result returned by the fopenfunction in your
program, you must define a variable of type “pointer to FILE.”
3.NULLis “officially” defined in the header file <stddef.h>;however, it is most likely also
defined in <stdio.h>.