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
to open the file and
associate it with our file variable.
As an example of using fopen():
fp = fopen("myfile", "r");
fpshould be declared as in:
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:
bcharacter to the open mode as in:
fp = fopen("myfile", "rb");
Notice that we declared the file variable as in:
fpis a pointer to a
FILE. The type
FILEis defined in the file
stdio.hthat 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
FILEstructure, loads it up with the relevant information and returns a pointer to it. If the open fails, then
There is one last thing we need to look at.
When we finish using a file, we should close it with
So for the file we opened above, we would execute the