Opening
files
A file is opened by a call to the
library function fopen(): this is available automatically when the library file
<stdio.h> is included. There are two stages to opening a file: firstly a
file portal must be found so that a program can access information from a file
at all. Secondly the file must be physically located on a disk or as a device
or whatever. The fopen() function performs both of these services and, if, in fact,
the file it attempts to open does not exist, that file is created anew. The
syntax of the fopen() function is:
FILE *returnpointer;
returnpointer =
fopen("filename","mode");
or
FILE returnpointer;
char *fname, *mode;
returnpointer = fopen(fname,mode);
The filename is a string which
provides the name of the file to be opened. Filenames are system dependent so
the details of this must be sought from the local operating system manual. The
operation mode is also a string, chosen from one of the following:
r
Open file for reading
w
Open file for writing
a
Open file for appending
rw
Open file for reading and writing (some systems)
This mode string specifies the way
in which the file will be used. Finally, returnpointer
is a pointer to a FILE structure which is the whole object of calling this
function. If the file (which was named) opened successfully when fopen() was called, returnpointer is a pointer to the file portal.
If the file could not be opened, this pointer is set to the value NULL.
This should be tested for, because it would not make sense to attempt to write
to a file which could not be opened or created, for whatever reason.
A read only file is opened, for
example, with some program code such as:
FILE
*fp;
if
((fp = fopen ("filename","r")) == NULL)
{
printf ("File could not be
opened\n");
error_handler();
}
A question which springs to mind is:
what happens if the user has to type in the name of a file while the program is
running? The solution to this problem is quite simple. Recall the function filename() which was written in chapter 20.
char
*filename() /*
return filename */
{
static char *filenm = "........................";
do
{
printf ("Enter filename :");
scanf ("%24s",filenm);
skipgarb();
}
while
(strlen(filenm) == 0);
return
(filenm);
}
This function makes file opening
simple. The programmer would now write something like:
FILE
*fp;
char
*filename();
if
((fp = fopen (filename(),"r")) == NULL)
{
printf ("File could not be
opened\n");
error_handler();
}
and then the user of the program
would automatically be prompted for a filename. Once a file has been opened, it
can be read from or written to using the other library functions (such as fprintf() and fscanf()) and then finally the file has to be closed again.
0 comments:
Post a Comment