为什么我不能像这样复制可执行文件?

问题描述:

使用C++的<fstream>,这是很容易复制的文本文件:为什么我不能像这样复制可执行文件?

#include <fstream> 

int main() { 
    std::ifstream file("file.txt"); 
    std::ofstream new_file("new_file.txt"); 

    std::string contents; 
    // Store file contents in string: 
    std::getline(file, contents); 
    new_file << contents; // Write contents to file 

    return 0; 
} 

但是,当你对可执行文件做同样的,输出可执行文件实际上并没有正常工作。也许std :: string不支持编码?

我希望我可以做下面的事情,但文件对象是一个指针,我不能解引用它(运行下面的代码创建new_file.exe实际上只包含一些东西的内存地址):

std::ifstream file("file.exe"); 
std::ofstream new_file("new_file.exe"); 

new_file << file; 

我想知道如何做到这一点,因为我认为这将是必不可少的局域网文件共享应用程序。我确定有更高级别的API用于使用套接字发送文件,但我想知道这些API实际上是如何工作的。

我可以逐位提取,存储和写入文件,因此输入和输出文件之间没有差异吗?感谢您的帮助,非常感谢。

+5

您需要为流构造函数的'openmode'参数传递'std :: ios :: binary'。将一个流的内容批量复制到另一个流的最佳方式是new_file ildjarn

+0

'std:string'是文本 - 不是二进制数据。二进制数据可以用'vector '或'basic_string '表示。试试看。 – Linuxios

+2

@Linuxios:'std :: string'可以包含任何'char'值,所以它能够保存二进制数据;这里的问题是流执行结束转换。 – ildjarn

不知道为什么ildjarn使它成为评论,但使它成为一个答案(如果他发布的答案,我会删除这个)。基本上,您需要使用未格式化的读写。 getline格式化数据。

int main() 
{ 
    std::ifstream in("file.exe", std::ios::binary); 
    std::ofstream out("new_file.exe", std::ios::binary); 

    out << in.rdbuf(); 
} 

技术上,operator<<为格式化数据,除了当像上面使用它。

在非常基本的方面:

using namespace std; 

int main() { 
    ifstream file("file.txt", ios::in | ios::binary); 
    ofstream new_file("new_file.txt", ios::out | ios::binary); 

    char c; 
    while(file.get(c)) new_file.put(c); 

    return 0; 
} 

虽然,你会更好做一个字符缓冲区,并使用ifstream::read/ofstream::write阅读和写一次块。