函数名: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("debug\\in.txt","r",stdin)的做用就是把标准输入流stdin重定向到debug\\in.txt文件中,这样在用scanf或是用cin输入时便不会从标准输入流读取数据,而是从in.txt文件中获取输入。只要把输入数据事先粘贴到in.txt,调试时就方便多了。
相似的,freopen("debug\\out.txt","w",stdout)的做用就是把stdout重定向到debug\\out.txt文件中,这样输出结果须要打开out.txt文件查看。
须要说明的是:
在freopen("debug\\in.txt","r",stdin)中,将输入文件in.txt放在文件夹debug中,文件夹debug是在VC中创建工程文件时自动生成的调试文件夹。若是改为freopen("in.txt","r",stdin),则in.txt文件将放在所创建的工程文件夹下。in.txt文件也能够放在其余的文件夹下,所在路径写正确便可。
以下代码为从文件从获取变量并将二者的和输入另外一个文件:
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
int a,b;
while(cin>>a>>b){
cout<<a+b<<endl;
}
fclose(stdin);
fclose(stdout);
return 0;
}ios