C++ 中 freopen()函数的用法

#include <stdio.h> 

#include <iostream> 

using namespace std;

 

int main() 

{ 

    int a,b; 

    freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取

    freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中

    while(cin>> a >> b) 

        cout<< a+b <<endl; // 注意使用endl

    fclose(stdin);//关闭文件

    fclose(stdout);//关闭文件

    return 0; 

}

  freopen("in.txt","r",stdin)的作用就是把标准输入流stdin重定向到in.txt文件中,这样在用scanf或是用cin输入时便不会从标准输入流读取数据,而是从in.txt文件中获取输入。 
类似的,freopen("out.txt","w",stdout)的作用就是把stdout重定向到out.txt文件中,这样输出结果需要打开out.txt文件查看。 

函数名:freopen 
声明:FILE *freopen( const char *path, const char *mode, FILE *stream ); 
所在文件: stdio.h 
参数说明: 
       path: 文件名,用于存储输入输出的自定义文件名。 
       mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。 
       stream: 一个文件,通常使用标准流文件。 
返回值:成功,则返回一个path所指定文件的指针;失败,返回NULL。(一般可以不使用它的返回值) 

功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。通过调用freopen,就可以修改标准流文件的默认值,实现重定向。

猜你喜欢

转载自www.cnblogs.com/Bella2017/p/11105136.html
今日推荐