Revision as of 08:45, 4 May 2011 by Ncapriol (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

 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:

    

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".

    F'ILE *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");

Alumni Liaison

Followed her dream after having raised her family.

Ruth Enoch, PhD Mathematics