繁体   English   中英

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

[英]Why can't I copy executables like this?

使用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;

我想知道如何执行此操作,因为我认为这在LAN文件共享应用程序中至关重要。 我确定有用于通过套接字发送文件的高级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读取和写入块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM