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");
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:
r
w
a
r+
w+
b
character to the open mode as in:
fp = fopen("myfile", "rb");
Notice that we declared the file variable as in:
FILE *fp;
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
fclose(fp);