📜  C++ freopen()

📅  最后修改于: 2020-09-25 08:22:21             🧑  作者: Mango

C++中的freopen() 函数尝试使用与另一个打开的文件相关联的文件流打开一个新文件。

freopen() 函数在头文件中定义。

freopen()原型

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

freopen 函数首先尝试关闭使用stream打开的文件。文件被关闭后,尝试打开由参数指定的文件名filename (如果它不为null)在参数指定的模式mode 。最后,它将文件与文件流stream关联。

如果filename是空指针,则freopen() 函数尝试重新打开已经与stream关联的文件。

freopen()参数

Different modes of file operation
File Access Mode Interpretation If file exists If file doesn’t exist
“r” Opens the file in read mode Read from start Error
“w” Opens the file in write mode Erase all the contents Create new file
“a” Opens the file in append mode Start writing from the end Create new file
“r+” Opens the file in read and write mode Read from start Error
“w+” Opens the file in read and write mode Erase all the contents Create new file
“a+” Opens the file in read and write mode Start writing from the end Create new file

freopen()返回值

freopen() 函数返回:

示例:freopen() 函数如何工作?

#include 
#include 

int main()
{
    FILE* fp = fopen("test1.txt","w");
    fprintf(fp,"%s","This is written to test1.txt");

    if (freopen("test2.txt","w",fp))
        fprintf(fp,"%s","This is written to test2.txt");
    else
    {
        printf("freopen failed");
        exit(1);
    }

    fclose(fp);
    return 0;
}

运行程序时:

The following will be written to test1.txt:
This is written to test1.txt
The following will be written to test2.txt:
This is written to test2.txt