[英]Why can't I copy executables like this?
Using C++'s <fstream>
, it's pretty easy to copy a text file: 使用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;
}
But when you do the same for an executable file, the output executable doesn't actually work. 但是,当您对可执行文件执行相同操作时,输出可执行文件实际上将无法工作。 Maybe std::string doesn't support the encoding? 也许std :: string不支持编码?
I was hoping that I could do something like the following, but the file object is a pointer and I'm not able to dereference it (running the following code creates new_file.exe which actually just contains the memory address of something): 我希望可以执行以下操作,但是文件对象是一个指针,并且无法取消引用它(运行以下代码将创建new_file.exe,它实际上仅包含某些内容的内存地址):
std::ifstream file("file.exe");
std::ofstream new_file("new_file.exe");
new_file << file;
I would like to know how to do this because I think it would be essential in a LAN file-sharing application. 我想知道如何执行此操作,因为我认为这在LAN文件共享应用程序中至关重要。 I'm sure there are higher level APIs for sending files with sockets, but I want to know how such APIs actually work. 我确定有用于通过套接字发送文件的高级API,但是我想知道此类API的实际工作方式。
Can I extract, store, and write a file bit-by-bit, so there's no discrepancy between the input and output file? 我可以逐位提取,存储和写入文件,这样输入和输出文件之间就不会有差异吗? Thanks for your help, it's much appreciated. 多谢您的协助,不胜感激。
Not sure why ildjarn made it a comment, but to make it an answer (if he posts an answer, I will delete this). 不知道为什么ildjarn对其进行评论,但是要使其成为答案(如果他发表了答案,我将其删除)。 Basically, you need to use unformatted reading and writing. 基本上,您需要使用无格式的读写。 getline
formats the data. getline
格式化数据。
int main()
{
std::ifstream in("file.exe", std::ios::binary);
std::ofstream out("new_file.exe", std::ios::binary);
out << in.rdbuf();
}
Technically, operator<<
is for formatted data, except when use it like the above. 从技术上讲, operator<<
用于格式化的数据, 除非像上述那样使用。
In very basic terms: 基本而言:
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;
}
Although, you'd be better off making a char buffer and using ifstream::read
/ ofstream::write
to read and write chunks at a time. 不过,最好还是制作一个char缓冲区并使用ifstream::read
/ ofstream::write
读取和写入块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.