如何附加到一个文件,然后将所述文件复制到另一个文件中

How to append to one file, then copy said file into another file

本文关键字:文件 另一个 然后 复制 何附加 一个      更新时间:2023-10-16

我觉得我什么都试过了,我可以把第一个文件附加到第二个文件,但不能把第二个附加到第三个文件。我做错了什么?

为了清楚起见,我需要取一个文件,将其附加到第二个文件中,然后将第二个文档的内容放入第三个文档中。我可以通过将两个文件都放入字符串,然后将这些字符串放入第三个文件来模拟这种结果,但这在这个问题中是不正确的。

我对任何方式或技术都不挑剔,我试过一些,但都不管用。这是最新的尝试,对于最后一步仍然不起作用。

这是我的代码:

#include <iostream>
#include <string> 
#include <fstream>
using namespace std;
int main()
{
    string a,b,c;
    cout << "Enter 3 file names: ";
    cin >> a >> b >> c;
    fstream inf;
    ifstream two;
    fstream outf;
    string content = "";
    string line = "";
    int i;
    string ch;
    inf.open(a, ios::in | ios:: out | ios::app);
    two.open(b);
    outf.open(c, ios::in);
    //check for errors
if (!inf)
    {
    cerr << "Error opening file" << endl;
    exit(1);
     } 
if (!two)
    {
    cerr << "Error opening file" << endl;
    exit(1);
    } 
if (!outf)
    {
    cerr << "Error opening file" << endl;
    exit(1);
    } 
 for(i=0; two.eof() != true; i++)
        content += two.get();
    i--;
    content.erase(content.end()-1);
    two.close();
    inf << content;
    inf.clear();
    inf.swap(outf);

    outf.close();
    inf.close();
    return 0;

这里有一个想法:

#include <fstream>
using namespace std;
void appendf( const char* d, const char* s )
{
  ofstream os( d, ios::app );
  if ( ! os )
    throw "could not open destination";
  ifstream is( s );
  if ( ! is )
    throw "could not open source";
  os << is.rdbuf();
}
int main()
{
  try
  {
    appendf( "out.txt", "1.txt" );
    return 0;
  }
  catch ( const char* x )
  {
    cout << x;
    return -1;
  }
}
相关文章: