📅  最后修改于: 2020-09-25 08:22:21             🧑  作者: Mango
freopen() 函数在
FILE* freopen( const char* filename, const char* mode, FILE* stream );
freopen 函数首先尝试关闭使用stream
打开的文件。文件被关闭后,尝试打开由参数指定的文件名filename
(如果它不为null)在参数指定的模式mode
。最后,它将文件与文件流stream
关联。
如果filename
是空指针,则freopen() 函数尝试重新打开已经与stream
关联的文件。
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() 函数返回:
#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