【问题标题】:How can I copy a text file into another? [duplicate]如何将文本文件复制到另一个文件中? [复制]
【发布时间】:2014-12-05 19:57:28
【问题描述】:

如何将文本文件复制到另一个文件中?我试过这个:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream infile("input.txt");
    ofstream outfile("output.txt");
    outfile << infile;

    return 0;
}

这最终会在output.txt 中留下以下值:0x28fe78

我做错了什么?

【问题讨论】:

  • 你必须从输入文件中读取,然后写入输出文件
  • &lt;&lt; infile 只会写出内部文件句柄标识符。例如在您运行代码时,input.txt 句柄的 id 为 0x28fe78
  • 改用outfile &lt;&lt; infile.rdbuf();
  • 您可以使用操作系统功能来执行此操作,例如 Linux cat 命令吗?
  • 这是另一个问题的子集:stackoverflow.com/questions/10195343/…

标签: c++ file stream


【解决方案1】:

您可以将 infile 的内容保存在一个字符串中,然后将其放入另一个文件中。 试试这个:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main ()
{
    ifstream infile("input.txt");
    ofstream outfile("output.txt");
    string content = "";
    int i;

    for(i=0 ; infile.eof()!=true ; i++) // get content of infile
        content += infile.get();

    i--;
    content.erase(content.end()-1);     // erase last character

    cout << i << " characters read...\n";
    infile.close();

    outfile << content;                 // output
    outfile.close();
    return 0;
}

最好的问候保罗

【讨论】:

    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    相关资源
    最近更新 更多