为什么我不能复制这样的可执行文件?
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;
我想知道如何做到这一点,因为我认为这在局域网文件共享应用程序中是必不可少的。我确信有更高级别的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
一次读取和写入块。
相关文章:
- CMake:我们可以为一组不形成可执行文件或库的特定文件指定包含目录吗?
- 错误:当我从"WinDbg"打开可执行文件时,找不到符号文件。默认导出 ntdll 的符号.dll
- 程序'main.exe'运行失败:指定的可执行文件不是此操作系统平台的有效应用程序
- X64 C 可执行文件不在纳米器码头容器中运行
- 我可以固定C 可执行文件,但不能共享库
- 为什么将可执行文件重命名为临时文件的此代码段不能按预期工作?
- C 可执行文件不从文件夹工作,而是在Mac上从控制台上工作
- 双击编译C++ Unix 可执行文件不会打开现有文件以从中读取信息
- 为什么当我键入名称时我的可执行文件不会运行?(Mac OS X Mountain Lion)Mac OS X 10.8.
- 为什么我不能复制这样的可执行文件?
- VIsual C++可执行文件不工作
- 如果可执行文件在两个或多个节点上运行,为什么它不能看到环境变量?
- >使用 RegCreateKeyEx() 的 Windows 可执行文件不会提示输入 UAC 管理员权限并失败?
- 用Visual Studio 11编译的可执行文件有什么特别之处,导致这些可执行文件不能在Windows XP上执行?
- 在调试c++程序时,QTCreator不能识别可执行文件
- C编译器不能创建可执行文件
- 不能从c++程序中调用可执行文件
- 使用 VS2010 构建的可执行文件不是有效的 win32 应用程序;bindump 说它是一个 DLL
- 保护可执行文件不受逆向工程的影响
- c++可执行文件不能在windows7-64位不兼容的环境下运行