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

Why can't I copy executables like this?

本文关键字:可执行文件 不能 复制 为什么      更新时间:2023-10-16

使用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实际上是如何工作的。

我可以一点一点地提取、存储和写入文件吗?这样输入和输出文件之间就不会有差异了?谢谢你的帮助,非常感谢。

不确定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;
}

不过,最好制作一个char缓冲区,并使用ifstream::read/ofstream::write一次读取和写入块。

相关文章: