C-style file input/output (std::fopen) (std::freopen) (std::fclose)

File access

Open file

std::fopen

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

Opens the file indicated by filename and returns the stream associated with the file. Use mode to determine the file access mode.

Parameters

filename The file name to which the file stream is to be associated
mode A null-terminated string that determines the file access mode
File access mode string Meaning Explanation Action if the file already exists Action if the file does not exist
"r" Read is read Get the open file Read from the beginning Open failed
"w" Write Create file for writing Destroy content Create new file
"a" Append Append to file Write to end Create new file
"r + " Extended read Open file for reading/writing Read from start Error
"w + " Extended Write Create file for reading/writing Destroy content Create new file
"a + " Extended append Open file for reading/writing Write to end Create new file
The file access mode flag "b" can optionally be specified to open the file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of ‘\
‘ and ‘\x1A’.
In append file access mode, writes data to the end of the file, ignoring the current position of the file position indicator.
The file access mode flag "x" can optionally be appended to the “w” or “w + ” specifier. This flag forces the function to fail if the file exists, rather than overwriting the file. (C++17)
If pattern is not one of the above strings, the behavior is undefined. Some implementations define additional

Return value

If successful, returns a pointer to the object controlling the open file stream and clears the end-of-file and error bits. The stream is fully buffered unless filename refers to an interactive device.

On error, a null pointer is returned. POSIX requires errno to be set in this case.

Attention

The format of filename is implementation-defined and does not necessarily refer to a file (for example, it could be the console or another device accessible through the file system API). On supported platforms, filename can contain absolute or relative file system paths.

For portable directory and file naming, see the C++ filesystem library or boost.filesystem .

Call example

#include <cstdio>
#include <cstdlib>

int main()
{
    FILE* fp = std::fopen("test.txt", "r");
    if (!fp)
    {
        std::perror("File opening failed");
        return EXIT_FAILURE;
    }

    int c; // Note: it is int instead of char, requiring EOF processing
    while ((c = std::fgetc(fp)) != EOF) // Standard C I/O file reading loop
    {
        std::putchar(c);
    }

    if (std::ferror(fp))
    {
        std::puts("I/O error when reading");
    }
    else if (std::feof(fp))
    {
        std::puts("End of file reached successfully");
    }

    std::fclose(fp);
    return 0;
}
Output

Open an existing stream with a different name

std::freopen

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

First, an attempt is made to close the file associated with the stream, ignoring any errors. Then, if filename is not empty, try to use mode to open the file specified by filename, as if using fopen, and then combine the file with stream. If filename is a null pointer, the function attempts to reopen the file already associated with stream (whether mode changes are allowed in this case is implementation-defined).

Parameters

filename The file to which the file stream is to be associated
mode Null-terminated string that determines the new file opening mode
File access mode string Meaning Explanation Action if the file already exists Action if the file does not exist
"r" Read is read Get the open file Read from the beginning Open failed
"w" Write Create file for writing Destroy content Create new file
"a" Append Append to file Write to end Create new file
"r + " Extended read Open file for reading/writing Read from start Error
"w + " Extended Write Create file for reading/writing Destroy content Create new file
"a + " Extended append Open file for reading/writing Write to end Create new file
The file access mode flag "b" can optionally be specified to open the file in binary mode. This flag has no effect on POSIX systems, but on Windows, for example, it disables special handling of ‘\
‘ and ‘\x1A’.
In append file access mode, writes data to the end of the file, ignoring the current position of the file position indicator.
The file access mode flag "x" can optionally be appended to the “w” or “w + ” specifier. This flag forces the function to fail if the file exists, rather than overwriting the file. (C++17)
If pattern is not one of the above strings, the behavior is undefined. Some implementations define additional supported modes (e.g. MSVC).
stream The file stream to be modified

Return value

stream on success, NULL on failure.

Attention

freopen is the only way to change the narrow/wide orientation of a stream once the orientation has been established by an I/O operation or std::fwide.

Call example

#include <cstdio>

int main()
{
    std::printf("stdout is printed to console\
");
    if (std::freopen("redir.txt", "w", stdout))
    {
        std::printf("stdout is redirected to a file\
"); // This is written to redir.txt
        std::fclose(stdout);
    }
    return 0;
}
Output

Close file

std::fclose

int fclose( std::FILE* stream );

Closes the given file stream. Flush any unwritten buffered data to the OS. Discard any unread buffered data.

Regardless of whether the operation is successful or not, the stream is no longer associated with the file, and buffers allocated by std::setbuf or std::setvbuf are also disassociated, if they exist, and deallocated if automatic allocation is used.

The behavior is undefined if the value of stream is used after fclose returns.

Parameters

stream The file stream to be closed

Return value

?0? on success, EOF otherwise.

Call example

#include <cstdio>
#include <cstdlib>

int main()
{
    FILE* fp = std::fopen("test.txt", "r");
    if (!fp)
    {
        std::perror("File opening failed");
        return EXIT_FAILURE;
    }

    int c; // Note: it is int instead of char, requiring EOF processing
    while ((c = std::fgetc(fp)) != EOF) // Standard C I/O file reading loop
    {
        std::putchar(c);
    }

    if (std::ferror(fp))
    {
        std::puts("I/O error when reading");
    }
    else if (std::feof(fp))
    {
        std::puts("End of file reached successfully");
    }

    std::fclose(fp);
    return 0;
}