读取可执行文件的部分数量失败

时间:2013-02-26 12:19:21

标签: c++ windows portable-executable

以下代码输出“段数: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;
}

1 个答案:

答案 0 :(得分:4)

istream_iterator使用operator<<unsuitable for binary data

请改用istream::read

您可以通过搜索结果获取文件大小,然后调用tellg。相应地调整矢量大小并直接读取它。