[英]How to read EXE bytes, store into a char array, and then write the bytes into a new EXE file?
I am trying to read bytes from an EXE file, send the bytes via socket, and then write the bytes into another EXE file. 我正在尝试从EXE文件读取字节,通过套接字发送字节,然后将字节写入另一个EXE文件。 The problem is that when I write the bytes to a EXE file and then try to open the EXE, Windows throws me an error:
问题是,当我将字节写入EXE文件然后尝试打开EXE时,Windows抛出错误:
Here is my code for reading the bytes from the original EXE file: 这是我的代码,用于从原始EXE文件读取字节:
if (newConnection == 0)
{
std::cout << "Error accepting connection\n\n" << std::endl;
}
else
{
std::cout << IP << " successfully connected to the client.\n\n" << std::endl;
std::ifstream fl("C:\\readbyte.exe");
fl.seekg(0, fl.end);
int length = fl.tellg();
char *buffer = new char[length];
fl.seekg(0, fl.beg);
fl.read((char*)buffer, length);
fl.close();
std::cout << buffer << std::endl;
send(newConnection, (char*)buffer, length, 0);
}
And here is my code for writing the bytes to a new EXE file: 这是我将字节写入新EXE文件的代码:
if (connect(Connection, (SOCKADDR*)&addr, sizeof(addr)) != 0) // if we are unable to connet
{
MessageBoxA(NULL, "Failed to connect", "Error", MB_OK | MB_ICONERROR);
}
else
{
std::cout << "Connected to server.\n" << std::endl;
std::vector<char> file(11776);
std::cout << "Test1" << std::endl;
if (recv(Connection, (char*)&file[0], file.size(), 0) < 0)
{
std::cout << "Test2" << std::endl;
puts("Recv failed\n");
system("pause");
return -1;
}
else
{
std::cout << "Test3" << std::endl;
std::cout << "File recieved: " << std::endl;
/*for (int i = 0; i < file.size(); i++)
{
std::cout << file[i];
if (int(file[i]) == 0)
{
file.erase(file.begin() + i);
}
}*/
const char *path = "C:/Users/Public/writefile.exe";
std::ofstream fout(path, std::ios::binary | std::ios::out);
fout.flush();
fout.write((char*)&file[0], file.size());
fout.close();
std::cout << "File size is: " << file.size() << std::endl;
closesocket(Connection);
}
I'm not sure what I am doing wrong. 我不确定自己在做什么错。 I've been working on this for 2 days now.
我已经为此工作了2天。
EDIT: ANSWER 编辑:答案
std::ifstream fl("C:\\readbyte.exe", std::ios::out | std::ios::binary);
I forgot to include std::ios::out | std::ios::binary
我忘了包括
std::ios::out | std::ios::binary
std::ios::out | std::ios::binary
in the server ifstream
. 服务器
ifstream
中的std::ios::out | std::ios::binary
。 I also switched the out and binary arguments around. 我还切换了out和binary参数。
以二进制模式打开文件(将std::ios::binary
作为ifstream
第二个参数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.