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

file access

open a file

std::fopen

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

Opens filenamethe file indicated by and returns the stream associated with the file. Use modeto determine the file access mode.

parameter

filename - The filename to associate the file stream to
mode - A null-terminated string that determines the file access mode
file access mode string meaning explain Action if file already exists Action if file does not exist
"r" read open file for reading read from start open failed
"w" Write Create file for writing destroy content create new file
"a" addition append to file write to the end create new file
"r+" extended read open file for reading/writing read from start mistake
"w+" extended write Create file for reading/writing destroy content create new file
"a+" extension append open file for reading/writing write to the 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 eg on Windows it disables special handling of '\n' and '\x1A'.
In append file access mode, writes data to the end of the file, ignoring the current position of the file position indicator.
File access mode flags "x"can optionally be appended to the "w" or "w+" specifiers. This flag forces the function to fail if the file exists, rather than rewriting the file. (C++17)
If mode is not one of the above strings, the behavior is undefined. Some implementations define additional

return value

On success, returns a pointer to the object controlling the open file stream, with the end-of-file and error bits cleared. Streams are fully buffered unless filename refers to an interactive device.

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

Notice

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

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; // 注意:是 int 而非 char ,要求处理 EOF
    while ((c = std::fgetc(fp)) != EOF)   // 标准 C I/O 文件读取循环
    {
        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 streamthe file associated with , ignoring any errors. Then, if filenamenon- null, an attempt is made to modeopen filenamethe file specified by by as if by fopen, and streamassociate the file with the file stream pointed to by . If filenameis a null pointer, the function attempts to reopen streamthe file already associated with (it is implementation-defined whether mode changes are allowed in this case).

parameter

filename - The file to associate the file stream to
mode - A null-terminated string that determines the new file opening mode

file access mode string meaning explain Action if file already exists Action if file does not exist
"r" read open file for reading read from start open failed
"w" Write Create file for writing destroy content create new file
"a" addition append to file write to the end create new file
"r+" extended read open file for reading/writing read from start mistake
"w+" extended write Create file for reading/writing destroy content create new file
"a+" extension append open file for reading/writing write to the 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 eg on Windows it disables special handling of '\n' and '\x1A'.
In append file access mode, writes data to the end of the file, ignoring the current position of the file position indicator.
File access mode flags "x"can optionally be appended to the "w" or "w+" specifiers. This flag forces the function to fail if the file exists, rather than rewriting the file. (C++17)
If mode is not one of the above strings, the behavior is undefined. Some implementations define additional supported modes (eg MSVC ).

stream - the file stream to modify

return value

on success stream, NULL on failure.

Notice

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

call example

#include <cstdio>

int main()
{
    std::printf("stdout is printed to console\n");
    if (std::freopen("redir.txt", "w", stdout))
    {
        std::printf("stdout is redirected to a file\n"); // 这被写入 redir.txt
        std::fclose(stdout);
    }
    return 0;
}

 output

close file

std::fclose

int fclose( std::FILE* stream );

Close the given file stream. Flush any unwritten buffered data to the OS. Any unread buffered data is discarded.

Regardless of the success of the operation, the stream is no longer associated with the file, and buffers allocated by std::setbuf or std::setvbuf are also deassociated, if present, and deallocated if automatic allocation was used.

The behavior is undefined if the value of fcloseis used after the return of stream.

parameter

stream - the file stream to close

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; // 注意:是 int 而非 char ,要求处理 EOF
    while ((c = std::fgetc(fp)) != EOF)   // 标准 C I/O 文件读取循环
    {
        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;
}

Guess you like

Origin blog.csdn.net/qq_40788199/article/details/132630830