zoukankan      html  css  js  c++  java
  • 【基础】文件读写

    #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
    ",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时不要忘记把与重定向有关的语句删除。

  • 相关阅读:
    软考数据库设计大观
    软考难点—算法时间的复杂度
    软考数据流图设计大观
    Android底部菜单的封装及重用
    在Action类中获得HttpServletResponse对象的四种方法
    java 单向加密算法
    ASP.NET下FCKeditor配置方法全解
    visual studio 2010 开发net 2.0 3.5项目
    android网络编程
    js 常用页面刷新
  • 原文地址:https://www.cnblogs.com/Kohinur/p/8524958.html
Copyright © 2011-2022 走看看