我正在尝试从EXE文件读取字节,通过套接字发送字节,然后将字节写入另一个EXE文件。问题是,当我将字节写入EXE文件然后尝试打开EXE时,Windows会向我抛出错误:
这是我的代码,用于从原始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);
}
这是我将字节写入新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);
}
我不确定自己在做什么错。我已经为此工作了2天。
编辑:答案
std::ifstream fl("C:\\readbyte.exe", std::ios::out | std::ios::binary);
我忘记在服务器std::ios::out | std::ios::binary
中包含ifstream
。
我还切换了out和binary参数。
答案 0 :(得分:1)
以二进制模式打开文件(将std::ios::binary
作为ifstream
的第二个参数)