C++判断pe文件实例
本文实例讲述了C++判断pe文件的方法。分享给大家供大家参考。
具体实现方法如下:
#include <afxdlgs.h>是为了使用CFileDialog
main.h如下:
#include <afxwin.h>
class CMyApp:public CWinApp
{
BOOL InitInstance();
};
main.cpp如下:
#include "main.h"
#include <afxdlgs.h>
CMyApp theApp;
BOOL CMyApp::InitInstance()
{
CFileDialog dlg(TRUE);
if (dlg.DoModal() != IDOK)
{
return FALSE;
}
//打开文件
HANDLE hFile = ::CreateFile(dlg.GetPathName(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile)
{
return FALSE;
}
IMAGE_DOS_HEADER dosHeader;
IMAGE_NT_HEADERS32 ntHeader;
DWORD dwReturn;
BOOL bIsPe=FALSE;
::ReadFile(hFile, &dosHeader, sizeof(IMAGE_DOS_HEADER), &dwReturn, NULL);
if (dwReturn == sizeof(IMAGE_DOS_HEADER))
{
if (dosHeader.e_magic == IMAGE_DOS_SIGNATURE) //mz
{
if (-1 != ::SetFilePointer(hFile, dosHeader.e_lfanew, NULL, FILE_BEGIN))
{
::ReadFile(hFile, &ntHeader, sizeof(IMAGE_NT_HEADERS32), &dwReturn, NULL);
if (dwReturn == sizeof(IMAGE_NT_HEADERS32))
{
if (ntHeader.Signature == IMAGE_NT_SIGNATURE) //pe
{
bIsPe = TRUE;
}
}
}
}
}
::CloseHandle(hFile); //与上面的CreateFile区对写
if (bIsPe)
{
MessageBoxA(NULL, "is a pe file", "", MB_OK);
}
else
{
MessageBoxA(NULL, "not a pe file", "", MB_OK);
}
return FALSE;
}
希望本文所述对大家的C++程序设计有所帮助。