Get Me the Elvis File

As we discussed in the previous part , each file has a file name. (And if you include the directory we usually call it the path name.) However, for most of the things we'll do to the file in our program, we won't be referring to it by that name. Instead, we will have a variable in the program that will identify the file we want to use.

There are several ways within standard C to associate a file with such a variable. We will focus on one method using the standard I/O library. We will use the function fopen() to open the file and associate it with our file variable. As an example of using fopen():

fp = fopen("myfile", "r");

Here the variable fp should be declared as in:
FILE *fp;

fopen() takes two arguments, both strings. The first argument is the file name (or path name). It may be a literal string (enclosed in double quotes) as we have here, or it may be an array of characters or even a character pointer. The second string is almost always a literal string (though it doesn't have to be) and it tells fopen() whether we want to read or write the file. The legal strings are:
open the file for reading and position at the beginning
open the file for writing and truncate it
open the file for writing and position at the end
open the file for both reading and writing positioned at the beginning
open the file for both reading and writing truncating it
open the file for both reading and writing positioned at the end
All of these apply for text files. If we want to open the file as a binary file, then we append a b character to the open mode as in:
fp = fopen("myfile", "rb");

Notice that we declared the file variable as in:

FILE *fp;

This says that fp is a pointer to a FILE . The type FILE is defined in the file stdio.h that we include at the beginning of every program. It describes a structure which contains the information that the I/O library needs to deal with the file. When we call fopen() , it finds an available FILE structure, loads it up with the relevant information and returns a pointer to it. If the open fails, then fopen() will return NULL .

There is one last thing we need to look at. When we finish using a file, we should close it with the fclose() call. So for the file we opened above, we would execute the statement


once we are done with the file.
Write an fopen() statement that opens the file whose name is in the array filename for reading and writing. It should be initially positioned at the beginning of the file and the file variable that we'll be using to refer to the file should be called file1 .