[Previous]
[Contents]
[Next]

fopen()

open a file

Synopsis:

#include <stdio.h>

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

Description:

The fopen() function opens the file whose name is the string pointed to by filename, and associates a stream with it. The argument mode points to a string beginning with one of the following sequences:

r
open file for reading
w
create file for writing, or truncate to zero length
a
append: open text file or create for writing at end-of-file
r+
open file for update (reading and/or writing); use default file translation
w+
create file for update, or truncate to zero length; use default file translation
a+
append; open file or create for update, writing at end-of-file; use default file translation

The letter b may be added to any of the above sequences in the second or third position to indicate that the file is (or must be) a binary file (an ANSI requirement for portability to systems that make a distinction between text and binary files). Under QNX, there's no difference between text files and binary files.


Note: When a stream is opened in update mode, both reading and writing may be performed. However, writing may not be followed by reading without an intervening call to the fflush() function, or to a file-positioning function (fseek(), fsetpos(), rewind()). Similarly, reading may not 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 the object controlling the stream. This pointer must be passed as a parameter to subsequent functions for performing operations on the file.

If the open operation fails, fopen() returns NULL. When an error has occurred, errno indicates the type of error detected.

Examples:

#include <stdio.h>

int main( void )
  {
    FILE *fp;

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

Classification:

ANSI
Safety:
Interrupt handler No
Signal handler No
Thread Yes

See also:

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


[Previous]
[Contents]
[Next]