Previous Page
Next Page

fopen

Opens a file

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

The fopen( ) function opens the file with the specified name. The second argument is a character string that specifies the requested access mode. The possible values of the mode string argument are shown in Table 17-1.

fopen( ) returns the FILE pointer for you to use in subsequent input or output operations on the file, or a null pointer if the function fails to open the file with the requested access mode.

Table 17-1. File access modes

Mode string

Access mode

Notes

"r"

"r+"

Read

Read and write

The file must already exist.

"w"

"w+"

Write

Write and read

If the file does not exist, fopen( ) creates it. If it does exist, fopen( ) erases its contents on opening.

"a"

"a+"

Append

Append and read

If the file does not exist, fopen( ) creates it.


When a file is first opened, the file position indicator points to the first byte in the file. If a file is opened with the mode string "a" or "a+", then the file position indicator is automatically placed at the end of the file before each write operation, so that existing data in the file cannot be written over.

If the mode string includes a plus sign, then the mode allows both input and output, and you must synchronize the file position indicator between reading from and writing to the file. Do this by calling fflush( ) or a file positioning functionfseek( ), fsetpos( ), or rewind( )after writing and before reading, and by calling a file-positioning function after reading and before writing (unless it's certain that you have read to the end of the file).

The mode string may also include b as the second or third letter (that is, "ab+" for example is the same as "a+b"), which indicates a binary file, as opposed to a text file. The exact significance of this distinction depends on the given system.

Example

FILE *in, *out;
int c;

if ( argc != 3 )
  fprintf( stderr, "Usage: program input-file output-file\n"), exit(1);

// If "-" appears in place of input filename, use stdin:
in  = (strcmp(argv[1], "-") == 0) ? stdin  : fopen(argv[1], "r");
if ( in == NULL )
  perror( "Opening input file" ), return -1;

// If "-" appears in place of output filename, use stdout:
out = (strcmp(argv[2], "-") == 0) ? stdout : fopen(argv[2], "a+");
if ( out == NULL )
  perror( "Opening output file" ), return -1;

while (( c = fgetc( in )) != EOF)
  if ( fputc(c, out) == EOF )
    break;

if ( !feof( in ))
  perror( "Error while copying" );
fclose(in), fclose(out);

See Also

fclose( ), fflush( ), freopen( ), setbuf( )


Previous Page
Next Page