C++ Premier Plus 6th edition - Programming excercise - Chapter17 - 4

// copy from 2 files to 1 file
// Approach 3: fin connect to 2 files, fout connect to 1 file
#include<iostream>
#include<fstream>
#include<string>

int main()
{
    using namespace std;
    const char* filename[3] = { "file1.txt","file2.txt","file3.txt" };// store file names
    fstream finout[3];// every one can handle both input and ouput stream

    // if can't open one of the files,not necessary to move on
    for (int i = 0; i < 3; i++)
    {
        if (i == 2)
            finout[i].open(filename[i], ios_base::in | ios_base::out|ios_base::app);// avoid file3 being covered
        else
            finout[i].open(filename[i]);

        if (!finout[i].is_open())
        {
            cerr << "Failed to open file: " << filename[i] << endl;
            exit(EXIT_FAILURE);
        }
    }
    // copy to
    while (!finout[0].eof() || !finout[1].eof())// after each getline(),input pointer steps forward
    {
        if (!finout[0].eof() && !finout[1].eof())// both file1 and file2 not reach eof
        {
            string str1, str2;// temp value
            getline(finout[0], str1);
            getline(finout[1], str2);
            finout[2] << str1 + " " + str2 + '\n';
        }

        if (!finout[0].eof() && finout[1].eof())// only file1 not reach eof
        {
            string str1;
            getline(finout[0], str1);
            finout[2] << str1 + '\n';
        }

        if (finout[0].eof() && !finout[1].eof())// only file2 not reach eof
        {
            string str2;
            getline(finout[1], str2);
            finout[2] << str2 + '\n';
        }
    }
    // disconnect
    for (int i = 0; i < 3; i++)
        finout[i].close();

    cout << "Copy completed. Bye!";
    cin.get();
    return 0;
}
/*
Approach 1: fin connect to 2 files, fout connect to 1 file. fin need to frequently
connect and disconnect,negative
Approach 2: finout connect to 3, will frequently connect and disconnect, negative
Approach 3: fin1 connect to file1, fin2 connect to file2, fout connect to file3
can also use command line int main(int argc,char* argv[n])
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值