freopen() 可用于流的重定向,函数原型为:
[C++] 纯文本查看 复制代码
#include <stdio.h>
FILE *freopen(const char *path, const char *mode, FILE *stream);
第 1 个参数 path 是一个文件路径。
第 2 个参数 mode 的值和fopen() 一样。
第 3 个参数 stream 是要被重定向的流,它会被重定向到 path 中去。
示例代码:
[C++] 纯文本查看 复制代码
#include <stdio.h>
int main()
{
FILE *fp;
printf ("This is output to STDOUT\n");
fp = freopen("myfile.txt", "w+", stdout);
printf ("STDOUT is redirected to myfile.txt\n");
fclose(fp);
return (0);
}
运行输出:> ./freopen
This is output to STDOUT
> cat myfile.txt
STDOUT is redirected to myfile.txt |