C++——流的文件I/O(Input & Output)

用流来对文件进行I/O操作,一定要先#include <fstream>

获取输入

基本框架
ifstream in_stream;
in_stream.open("in_stream.dat");
...
in_stream.close();
检查输入
  • 在进一步对输入进行操作前应该先判断一下输入文件是否成功打开,成功则继续,否则退出,在这里对输入/输出流对象使用fail 成员函数
//输入流判断
if(in_stream.fail())
    {
        cout << "input error.\n" << endl;
        exit(1);
    }
//输出流判断
if(out_stream.fail())
    {
        cout << "output error.\n" << endl;
        exit(1);
    }

生成输出

基本框架
ofstream out_stream;
out_stream.open(out_stream.dat);
...
out_stream.close();
追加输出(不覆盖已有文件)
  • 流以文件的形式输出的时候默认输出一个新文件——也就是说,如果已经存在一个同名文件,就会被新生成的文件覆盖掉。但有的时候我们需要多次运行来多次采集数据而不覆盖之前的记录,则可以更改成员函数open
out_stream.open("out_stream.dat",ios::app);
  • 但注意,在加入ios::app 参数之前,一定要先引入<iostream>

完整代码

#include "iostream"
#include "fstream"
#include "cstdlib"
using namespace std;

int main(int argc, char const *argv[])
{
    char In_File_Name[16],Out_File_Name[16];
    ifstream In_Stream;
    ofstream Out_Stream;

    cout << "I will sum three numbers taken from an input" << endl
         << "file and write the sum to an output file" << endl;
    cout << "Enter the input file name(maximum of 15 characters):" << endl;
    cin >> In_File_Name;
    cout << "Enter the output file name(maximum of 15 characters):" << endl;
    cin >> Out_File_Name;
    cout << "I will read numbers from the file"
         << In_File_Name << " and" <<endl
         << "place the sum in the file "
         << Out_File_Name << endl;

    In_Stream.open(In_File_Name);
    if(In_Stream.fail())
    {
        cout << "Input file opening error!" << endl;
        exit(1);
    }

    Out_Stream.open(Out_File_Name);
    if(Out_Stream.fail())
    {
        cout << "Output file opening error!" << endl;
        exit(1);
    }

    int first,second,third;
    In_Stream >> first >> second >> third;
    Out_Stream << "The sum of input is " << (first + second + third) << endl;

    In_Stream.close();
    Out_Stream.close();

    cout << "Programme run successfully!" << endl;
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值