windwos 判断文件架构

原理:通过文件头来判断文件类型和架构 和 DOS下exe头文件解析

下面直接上代码:

//0x0001-dll 0x0002-exe 
//0x0010-x32 0x0020-x64
bool get_file_arch(const char* szdllexe, int &ft)
{
    ft = 0;
    FILE* fp = fopen(szdllexe,"r+b");
    if (fp == nullptr) return false;

#define RT_RES(res)\
{fclose(fp); return res;}

    IMAGE_DOS_HEADER dosHeader = {0};
    size_t iread = fread(&dosHeader, 1, sizeof(dosHeader), fp);
    if (iread != sizeof(dosHeader)) RT_RES(false);
    //MZ file is exe or dll
    if (dosHeader.e_magic != IMAGE_DOS_SIGNATURE) RT_RES(false);
    //read PE header
    fseek(fp, dosHeader.e_lfanew + 4, SEEK_SET);

    IMAGE_FILE_HEADER imgHeader = { 0 };
    iread = fread(&imgHeader, 1, sizeof(imgHeader), fp);
    if (iread != sizeof(imgHeader)) RT_RES(false);

   	if (imgHeader.Characteristics & IMAGE_FILE_DLL) ft |= 0x0001;
	else if (imgHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) ft |= 0x0002;

    if (imgHeader.Characteristics & IMAGE_FILE_32BIT_MACHINE) ft |= 0x0010;
    else ft |= 0x0020;
   
    RT_RES(true);
}

你可能感兴趣的:(C++,随笔,exe,dll,架构,PE)