【问题标题】:how to read from a file and append it to the end of another file in c++ [duplicate]如何从文件中读取并将其附加到c ++中另一个文件的末尾[重复]
【发布时间】:2018-04-06 11:34:20
【问题描述】:

我打开了两个文件,我想找到将数据从输出文件放入填充的最有效方法。 我尝试了rdbuf(),但它不起作用,并且输出文件相同,所以我需要对rdbuf() 进行更多解释,还有其他方法可以将文件附加到另一个文件吗?

ofstream writeto;
writeto.open(srr.c_str(),ios::app);
cout<<"give me the file you want to copy from  : ";
string written;
cin>>written;
ifstream writefrom;
writefrom.open(written.c_str());

【问题讨论】:

    标签: c++


    【解决方案1】:

    假设您要复制整个输入文件:

    writeto << writefrom.rdbuf();
    

    此外,您应该使用std::getline() 而不是operator&gt;&gt;,这样您就可以考虑其中包含空格字符的文件路径/名称:

    getline(cin, written);
    

    【讨论】:

    • 我试过 writefrom.rdbuf() 但文件没有改变,所以我在这里要求获得另一个答案或知道为什么这不起作用
    • std::ofstream 有一个operator&lt;&lt;,它接受一个std::basic_streambuf* 作为输入。 std::ifstream::rdbuf() 返回一个std::basic_filebuf*,而std::basic_filebuf 派生自std::basic_streambuf,所以它应该可以工作。你确认writeto.open()writefrom.open() 都成功了吗?您显示的代码中没有错误处理。
    【解决方案2】:

    将一个文件读入流对象,将下一个文件读入流中。写出流。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2014-05-11
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      相关资源
      最近更新 更多