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

时间:2016-03-29 12:13:12

标签: c++ file-io

我觉得我已经尝试了所有东西,我可以将第一个文件追加到第二个文件但是不能将第二个文件放到第三个文件中。我究竟做错了什么?

要清楚我需要获取一个文件,将其附加到第二个文件,然后将第二个文件的内容放入第三个文件中。我能够通过将两个文件放入字符串然后将这些字符串放入第三个文件来模拟这个结果,但在这个问题上这不是'正确'。

我不是特别关注任何方式或任何技术,我尝试了一些,没有任何作用。这是最新的尝试,仍然不适用于最后一步。

这是我的代码:

#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;

1 个答案:

答案 0 :(得分: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;
  }
}
相关问题