c++ - 如何将文本文件复制到另一个文件?

标签 c++ file stream

<分区>

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

#include <iostream>
#include <fstream>

using namespace std;

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

    return 0;
}

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

我做错了什么?

最佳答案

您可以将输入文件的内容保存在一个字符串中,并将该字符串打印到输出文件中。 试试这个:

#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(); i++)     // get content of infile
        content += infile.get();
    infile.close();

    content.erase(content.end()-1);  //  last read character is invalid, erase it
    i--;

    cout << i << " characters read...\n";

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

关于c++ - 如何将文本文件复制到另一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26302949/

相关文章:

c++ - luaL_dofile 错误

c++ - ipv6 向后兼容 ipv4 吗?

c# - 在 C# 中使用 FileSystemWatcher 确定复制/写入进度

Java - 在持久性媒体中存储整数的快速方法

c++ - cin 是否在输入流中采用空字符?

c# - Windows 文件系统?

c++ - cv::perspectiveTransform 断言失败

c - 为什么我的程序 fork 函数没有按预期运行

c++ - memorystream - stringstream,字符串,其他?

http - 在 Golang 中没有缓冲 http.ResponseWritter