【基础】文件读写

Posted on 2018-03-07 19:59  som_nico  阅读(188)  评论(0编辑  收藏  举报
#include <stdio.h>
int main()
{
    int a,b;//标准输入stdin、标准输出stdout
    freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
    freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
    while(scanf("%d %d",&a,&b)!=EOF)
        printf("%d\n",a+b);
    fclose(stdin);//关闭文件
    fclose(stdout);//关闭文件
    return 0;
}

C++语法 

#include <stdio.h> 
#include <iostream.h> 
int main() 
{ 
int a,b; 
freopen("debug\\in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取 
freopen("debug\\out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中 
while(cin>>a>>b) 
cout<<a+b<<endl; // 注意使用endl 
fclose(stdin);//关闭文件 
fclose(stdout);//关闭文件 
return 0; 
} 

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文件查看。 

需要说明的是: 
1. 在freopen("debug\\in.txt","r",stdin)中,将输入文件in.txt放在文件夹debug中,文件夹debug是在VC中建立工程文件时自动生成的调试文件夹。如果改成freopen("in.txt","r",stdin),则in.txt文件将放在所建立的工程文件夹下。in.txt文件也可以放在其他的文件夹下,所在路径写正确即可。 
2. 可以不使用输出重定向,仍然在控制台查看输出。 
3. 程序调试成功后,提交到oj时不要忘记把与重定向有关的语句删除。