Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ <cstdio> fopen() function opens a file indicated by filename and returns a file stream associated with that file. The mode is used to determine the file access mode.

The file stream can be disassociated from the file by calling fclose() or freopen() function. All opened files are automatically closed on normal program termination.

Syntax

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

Parameters

filename Specify file name to associate the file stream to. It can include a path (if supported by the system).
mode Specify C string containing a file access mode. See the below table for more details.

ModesDescriptionAction: If file existsAction: If file does not exist
"r" Read: open a file for reading Read from startFailure to open
"w" Write: create a file for writing Delete contentsCreate new
"a" Append: Append to a file Write to endCreate new
"r+" Read extended: open a file for read/write read from startError
"w+" Write extended: create a file for read/write Delete contentsCreate new
"a+" Append extended: open a file for read/write Write to endCreate new

  • The above discussed mode specifiers opens a file as a text file. To open a file as a binary file, a "b" character has to be included in the mode string. This additional "b" character can either be appended at the end of the string ("rb", "wb", "ab" OR "r+b", "w+b", "a+b") or be inserted between the letter and the "+" sign for the mixed modes ("rb+", "wb+", "ab+").
  • File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it (since C++17).
  • The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes.

Return Value

On success, returns a pointer to a FILE object that can be used to identify the stream on future operations. On error, returns a null pointer. On most library implementations, the errno variable is also set to a system-specific error code on failure.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
This is a test file.

In the below example, file is opened using fopen() to read the content of the file.

#include <cstdio>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //first character in the file
  int c = getc(pFile);
  
  //if first character is not EOF, reads and writes
  //characters from the file until EOF is not reached
  while (c != EOF) {
    putchar(c);
    c = getc(pFile);
  }
  
  //close the file
  fclose(pFile);

  return 0;
}

The output of the above code will be:

This is a test file.
This is a test file.

❮ C++ <cstdio> Library

5