Node:Opening a file, Next:Closing a file, Previous:High-level file routines, Up:High-level file routines
The main high-level function for opening files is fopen
. When
you open a file with the fopen
function, the GNU C Library
creates a new stream and creates a connection between the stream and a
file. If you pass this function the name of a file that does not exist,
that file will be created. The fopen
function normally returns a
stream. A stream is a flow of data from a source to a destination
within a GNU system. Programs can read characters from or write
characters to a stream without knowing either the source or destination
of the data, which may be a file on disk, a device such as a terminal
meant as a human interface, or something entirely different. Streams
are represented by variables of type FILE *
-- fopen
will
return a null pointer if it fails to open the file.
The first parameter to this function is a string containing the filename
of the file to open. The filename string can be either a constant or a
variable, as in the following two equivalent examples:
FILE *my_stream; my_stream = fopen ("foo", "r"); FILE *my_stream; char my_filename = "foo"; my_stream2 = fopen (my_filename, "r");
The second parameter is a string containing one of the following sets of characters:
r
w
r+
w+
a
a+
See File position, for more information on the concept of file position.
You can also append the character x
after any of the strings in the
table above. This character causes fopen
to fail rather than opening
the file if the file already exists. If you append x
to any of the arguments
above, you are guaranteed not to clobber (that is, accidentally destroy)
any file you attempt to open. (Any other characters in this parameter are ignored
on a GNU system, but may be meaningful on other systems.)
The following example illustrates the proper use of fopen
to open
a text file for reading (as well as highlighting the fact that you
should clean up after yourself by closing files after you are done with
them). Try running it once, then running it a second time after
creating the text file snazzyjazz.txt
in the current directory
with a GNU command such as touch snazzyjazz.txt
.
#include <stdio.h> int main() { FILE *my_stream; my_stream = fopen ("snazzyjazz.txt", "r"); if (my_stream == NULL) { printf ("File could not be opened\n"); } else { printf ("File opened! Closing it now...\n"); /* Close stream; skip error-checking for brevity of example */ fclose (my_stream); } return 0; }
See Closing a file, for more information on the function fclose
.