[Previous] [Contents] [Next]

fopen()

Open a file stream

Synopsis:

#include <stdio.h>

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

Library:

libc

Description:

The fopen() function opens a file stream for the file specified by filename. The mode string begins with one of the following sequences:

a
Append: create a new file or open the file for writing at its end.
a+
Append: open the file or create it for update, writing at end-of-file; use the default file translation.
r
Open the file for reading.
r+
Open the file for update (reading and/or writing); use the default file translation.
w
Create the file for writing, or truncate it to zero length.
w+
Create the file for update, or truncate it to zero length; use the default file translation.

You can add the letter b to the end of any of the above sequences to indicate that the file is (or must be) a binary file (this is an ANSI requirement for portability to systems that make a distinction between text and binary files, such as DOS). Under QNX, there's no difference between "text" files and "binary" files.


Note: When using a stream in update mode, writing can't be followed by reading without an intervening call to fflush(), or to a file-positioning function (fseek(), fsetpos() or rewind()). Similarly, reading can't be followed by writing without an intervening call to a file-positioning function, unless the read resulted in end-of-file.

Returns:

A pointer to a file stream for success, or NULL if an error occurs (errno is set).

Examples:

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    FILE *fp;

    fp = fopen( "report.dat", "r" );
    if( fp != NULL ) {
        /* rest of code goes here */
        fclose( fp );
        
        return EXIT_SUCCESS;
    }

    return EXIT_FAILURE;
}

Classification:

ANSI

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fclose(), fcloseall(), fdopen(), freopen()


[Previous] [Contents] [Next]