【问题标题】:Reading number of sections of an executable fails读取可执行文件的节数失败
【发布时间】:2013-02-11 21:29:51
【问题描述】:

以下代码不知何故输出了“节数:57344”,这显然是不正确的。谁能给我一个提示我做错了什么?

#include <windows.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>

int main() {
std::string file_path = "C:\\foo.exe";
if(!file_path.size()) {
    cout << "No file was selected" << endl;
    return 1;
}
std::ifstream input( file_path.c_str(), std::ios::binary );
std::vector<unsigned char> buffer((
    std::istream_iterator<unsigned char>(input)), 
    (std::istream_iterator<unsigned char>()));

if(!buffer.size()) {
    cout << "Error reading file" << endl;
    return 1;
}
char * BinFile = (char*)&buffer[0];
IMAGE_DOS_HEADER* DOSHeader = (IMAGE_DOS_HEADER*)BinFile;
IMAGE_NT_HEADERS* NTHeader = (IMAGE_NT_HEADERS*)(BinFile + DOSHeader->e_lfanew);
cout << "Number of sections: " << NTHeader->FileHeader.NumberOfSections << endl;

return 0;
}

【问题讨论】:

标签: c++ windows portable-executable


【解决方案1】:

istream_iterator 使用 operator&lt;&lt;unsuitable for binary data 一样

请改用istream::read

您可以通过查找到最后,然后调用tellg 来获取文件大小。相应地调整向量的大小并直接读取它。

【讨论】:

  • @Listing 这真的很常见。使用 c++ 流不正确地读取二进制文件有多少错误:D
猜你喜欢
  • 1970-01-01
  • 2010-11-30
  • 2016-09-17
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多