Previous Page
Next Page

13.3. Opening and Closing Files

To write to a new file or modify the contents of an existing file, you must first open the file. When you open a file, you must specify an access mode indicating whether you plan to read, to write, or some combination of the two. When you have finished using a file, close it to release resources.

13.3.1. Opening a File

The standard library provides the function fopen( ) to open a file. For special cases, the freopen( ) and tmpfile( ) functions also open files.

    FILE *fopen( const char * restrict filename, const char * restrict mode );

This function opens the file whose name is specified by the string filename. The filename may contain a directory part. The second argument, mode, is also a string, and specifies the access mode. The possible access modes are described in the next section. The fopen( ) function associates the file with a new stream.

    FILE *freopen( const char * restrict filename, const char * restrict mode,
                   FILE * restrict stream );

This function redirects a stream. Like fopen( ), freopen( ) opens the specified file in the specified mode. However, rather than creating a new stream, freopen( ) associates the file with the existing stream specified by the third argument. The file previously associated with that stream is closed. The most common use of freopen( ) is to redirect the standard streams, stdin, stdout, and stderr.

    FILE *tmpfile( void );

The tmpfile( ) function creates a new temporary file whose name is distinct from all other existing files, and opens the file for binary writing and reading (as if the mode string "wb+" were used in an fopen( ) call). If the program is terminated normally, the file is automatically deleted.

All three file-opening functions return a pointer to the stream opened if successful, or a null pointer to indicate failure.

13.3.2. Access Modes

The access mode specified by the second argument to fopen( ) or freopen( ) determines what input and output operations the new stream permits. The permissible values of the mode string are restricted. The first character in the mode string is always r for "read," w for "write," or a for "append," and in the simplest case, the string contains just that one character. However, the mode string may also contain one or both of the characters + and b (in either order: +b has the same effect as b+).

A plus sign (+) in the mode string means that both read and write operations are permitted. However, a program must not alternate immediately between reading and writing. After a write operation, you must call the fflush( ) function or a positioning function (fseek( ), fsetpos( ), or rewind( )) before performing a read operation. After a read operation, you must call a positioning function before performing a write operation.

A b in the mode string causes the file to be opened in binary modethat is, the new stream associated with the file is a binary stream. If there is no b in the mode string, the new stream is a text stream.

If the mode string begins with r, the file must already exist in the file system. If the mode string begins with w, then the file will be created if it does not already exist. If it does exist, its previous contents will be lost, because the fopen( ) function truncates it to zero length in "write" mode.

A mode string beginning with a (for append) also causes the file to be created if it does not already exist. If the file does exist, however, its contents are preserved, because all write operations are automatically performed at the end of the file. Here is a brief example:

    #include <stdio.h>
    #include <stdbool.h>
    _Bool isReadWriteable( const char *filename )
      FILE *fp = fopen( filename, "r+" );  // Open a file to read and write.

      if ( fp != NULL )                    // Did fopen( ) succeed?
        fclose(fp);                  // Yes: close the file; no error handling.
        return true;
      else                           // No.
        return false;

This example also illustrates how to close a file using the fclose( ) function.

13.3.3. Closing a File

To close a file, use the fclose( ) function. The prototype of this function is:

    int fclose( FILE *fp );

The function flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the stream's input and output buffers. The fclose( ) function returns zero on success, or EOF if an error occurs.

When the program exits, all open files are closed automatically. Nonetheless, you should always close any file that you have finished processing. Otherwise, you risk losing data in the case of an abnormal program termination. Furthermore, there is a limit to the number of files that a program may have open at one time; the number of allowed open files is greater than or equal to the value of the constant FOPEN_MAX.

Previous Page
Next Page