Revision as of 09:53, 4 May 2011 by Ncapriol (Talk | contribs)

 Dealing with Files in C

There are two main types of files dealt with in ECE264: binary files and text files.  A text file contains characters and is similar to a word processing document, but usually without the formatters. A binary file, on the other hand, can contain any kind of data (from text to even images in movies) but is encoded in the binary format (which uses only 0s and 1s).

There are a few subtle differences as to how binary and text files are handled within a C Program. These differences are summarized in the chart below and discussed in further detail below.

reading writing opening
text files fgetc, fgets fprintf, fputc "r","w"
binary files fread fwrite "rb","wb"

Opening File

To open a file, you must create a file-pointer for the system.  You can simply do this by saying:

    FILE *f = NULL;

Files in C are opened using the fopen command.  Fopen requires two arguments with it. The first one is the file name that you wish to be opened, followed by a comma, and then what you want to do with the file. If you wish to read a text file (and NOT write back to the file), the second argument would simply be "r".

   FILE *f = fopen(filename, "r");

If you wanted to open a binary file for reading, the command is similar but the second argument changes to "rb".  The "b" placed behind the "r" tells the system that you will be reading a binary file.

    FILE *f = fopen(filename, "rb")


If you wanted to open a file for writing to, the fopen command is changed to a "w" instead of an "r". If utilizing a binary file, the appending "b" is kept onto the command.

     FILE *f = fopen(filename, "w");

     FILE *f = fopen(filename,"wb");

Note that "writing" to a file will create the file if it does not exist. If the file does exist, however, the system will erase the existing contents of the file and will then write whatever you want to it. If you want to add something to an existing file while still preserving its existing contents, you can use the "a" command to append a file, but that utilization does not fall into the purview of this class.

Reading a File

Closing a File

Regardless of whether a file is in binary or text, the file must be closed when you are finished with it. The closing procedure uses fclose and is identical for binary and text files:

     fclose(f); [where f is your filehandle from when you opened your file]

Alumni Liaison

Have a piece of advice for Purdue students? Share it through Rhea!

Alumni Liaison