UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

9.2.2.  Opening a file

The function fopen opens a file and associates a stream with that opened file. You need to specify the method of opening the file and the filename as arguments.

#include <stdio.h>
FILE *fopen(const char *filename, const char *mode);

Here filename is a char pointer that references a string containing a filename. mode points to another string that specifies the way to open the file. The fopen function returns a pointer of type FILE. If an error occurs during the procedure to open the file, the fopen function returns NULL.

The mode parameter is a combination of the characters r (read), w (write), b (binary), a (append), and + (update). When you use the a character and the file already exists, the contents of the file will be preserved and new data that you write will be added to the end. If the file does not already exist, it will be created. This is in contrast to w; this mode discards any data that may already be in the file (if the file does not exist, it creates a new one). Using the + character sets the mode to both reading and writing and you can modify any data in it. When you use r, the file must already exist; if it does not, the call will fail and returns NULL.

The following list shows the possible modes to open a file:

  • "r" opens an existing text file for reading.

  • "w" creates a text file for writing.

  • "a" opens an existing text file for appending.

  • "r+" opens an existing text file for reading or writing.

  • "w+" creates a text file for reading or writing.

  • "a+" opens or create a text file for appending.

  • "rb" open an existing binary file for reading.

  • "wb" creates a binary file for writing.

  • "ab" opens an existing binary file for appending.

  • "r+b" opens an existing binary file for reading or writing.

  • "w+b" creates a binary file for reading or writing.

  • "a+b" opens or creates a binary file for appending.

You might see code where the mode is given as "rb+" instead of "r+b", for example, but these two strings are equivalent.

Answer the following questions to see if you understood what the content of this document:

  • What does the following expression do?:

    fopen(“text.bin”, ”r+b”);
    • Open an existing file to read and write

    • Creates a binary file to read and write.

    • Open an existing file to read and append data at the end.

    • Creates a binary file to read and append data at the end.

    • None above.