版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/89405596
函数名:freopen
声明:FILE *freopen( const char *path, const char *mode, FILE *stream );
参数说明:
path: 文件名,用于存储输入输出的自定义文件名。
mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。
stream: 一个文件,通常使用标准流文件。
返回值:
成功,则返回一个path所指定文件的指针;失败,返回NULL。(一般不使用它的返回值)
功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。通过调用freopen,就可以修改标准流文件的默认值,实现重定向。
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char ch;
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
while ((ch=getchar())!=EOF){
putchar(ch);
}
fclose(stdin);
fclose(stdout);
return 0;
}