freopen - C stdio.h

C examples for stdio.h:freopen

Type

function

From


<cstdio>
<stdio.h>

Description

Reopen stream with different file or mode

Prototype

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

Parameters

ParameterDescription
filename C string containing the file name.
mode C string containing a file access mode.
stream pointer to a FILE object that identifies the stream to be reopened.

The mode can be:

Value Action Description
"r"read Open file for reading. The file must exist.
"w"write Create an empty file for writing. If the file already exists, empty the existing file.
"a"appendOpen file for appending. The file is created if it does not exist.
"r+" read/update Open a file both for input and output. The file must exist.
"w+" write/update Create an empty file and open it both for input and output. If the file already exists, empty the existing file.
"a+" append/update Open a file both for input and output, append to the end of the file. The file is created if it does not exist.

With the mode specifiers above the file is open as a text file.

In order 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.

It makes the following compound modes: "rb", "wb", "ab", "r+b", "w+b", "a+b") or ("rb+", "wb+", "ab+").

Return Value

On success, the function returns the pointer for the reopened stream.

Otherwise, a null pointer is returned.

Example

The following code code reopened main.cpp file and redirected stdout:

Demo Code


#include <stdio.h>

int main ()// w ww . j  a  va2  s  .  co  m
{
  freopen ("main.cpp","w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}

Related Tutorials