File Access: fopen Function

Download a copy of the weblog itself. Put it in the directory that will contain the C project that you are about to build. The file can be downloaded here:

FriedSpace Weblog (friedspace.txt)

In order to have our C program open this file, we use the fopen command from the stdio library. It takes two arguments. The first is a string containing the filename of the file we are opening whilst the second is a mode string which tells the operating system what we intend to do with the file. This mode string consists of an "r", "w" or "a" followed by a "+", "b" or both. The meaning of these letters is as follows:

"r" opens an existing file for reading
"w" creates a new file or opens an existing file for (over)writing. "a" creates a new file or opens an existing file for appending (i.e. each new write starts at the end of the file, appending data to what is already there)

The default for each of these modes is to open a text file. Therefore we can follow each of these with:

"b" open the file as a binary file (i.e. the file doesn't consist solely of strings terminated with a carriage return, but may consist of other data types as well, and may contain no carriage returns at all).

Finally, we may wish to read and write to a file, so to any of the above modes we can add:

"+" open the file for reading and writing.

Since it is inconvenient to refer to our open file by its full name all the time, the return value of fopen is a file handle (basically a unique number) which identifies our file in all subsequent accesses to C file functions. The variable type of a file handle is just FILE *. Therefore we must declare a variable of type FILE * to store the file handle that is returned by fopen.

Our weblog file is a text file and we will only want to read from it, so we can use the following lines to open the file for reading:

FILE * weblog;

weblog = fopen("friedspace.txt","r");

If we wanted to open it for reading and writing, and it was in fact a binary file, we would replace this last line with:

weblog = fopen("friedspace.txt","rb+");