//往文件末尾写数据
//找到PE文件末尾
UINT PublicFuntion::FindEndOfPE()
{
IMAGE_DOS_HEADER st_dos_header;
memset(&st_dos_header,0,sizeof(IMAGE_DOS_HEADER));
int i_count = sizeof(IMAGE_DOS_HEADER);
//返回的是相应可执行文件或dll文件加载到进程地址空间的句柄(基地址);
//传入NULL返回进程地址空间中可执行文件的基地址。
HMODULE hMod = GetModuleHandle(NULL);
PIMAGE_DOS_HEADER lpImageDosHeader = NULL;
//SECTION TABLE
PIMAGE_SECTION_HEADER lpImageSectionHeader = NULL;
PIMAGE_FILE_HEADER lpImageFileHeader = NULL;
//==Dos header 文件指针
lpImageDosHeader = (PIMAGE_DOS_HEADER)hMod;
//==新exe头部的文件地址,一个4字节的文件偏移量;==
lpImageFileHeader = (PIMAGE_FILE_HEADER)((BYTE *)hMod + lpImageDosHeader->e_lfanew + 4);
int SectionNums = lpImageFileHeader->NumberOfSections;
lpImageSectionHeader = (PIMAGE_SECTION_HEADER)((BYTE *)hMod + lpImageDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER)* (SectionNums-1));
DWORD rawData = lpImageSectionHeader->PointerToRawData;
DWORD sizeifrawdata = lpImageSectionHeader->SizeOfRawData;
//PE文件结尾
return rawData + sizeifrawdata;
}
//从PE文件末尾读取数据
void PublicFuntion::ReadPEFromExe(CString _strFile,CString &_strMsg)
{
#ifdef TCHAR
TCHAR strPath[MAX_PATH];
wcscpy(strPath, L"d:\\1.exe");
#else
char strPath[MAX_PATH];
strcpy(strPath, _strFile.GetBuffer(_strFile.GetLength()));
#endif
HANDLE handle = CreateFile(strPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
if (handle == INVALID_HANDLE_VALUE)
{
AfxMessageBox("资源文件不存在,打开错误");
return ;
}
LARGE_INTEGER li;
li.QuadPart = FindEndOfPE();
SetFilePointerEx(handle, li, NULL, FILE_BEGIN);
char string[256];
memset(string,0,sizeof(string));
DWORD m_dwNumToRead = 0;
ReadFile(handle, string, MAX_PATH, &m_dwNumToRead, NULL) ;
// MessageBox(string);
_strMsg=string;
CloseHandle(handle);
}
void PublicFuntion::WritePE2Exe(CString _strFile,CString _strMsg)
{
#ifdef TCHAR
TCHAR strPath[MAX_PATH];
wcscpy(strPath, "d:\\1.exe");
#else
char strPath[MAX_PATH];
strcpy(strPath, _strFile.GetBuffer(_strFile.GetLength()));
#endif
HANDLE handle = CreateFile(strPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
if(handle == INVALID_HANDLE_VALUE)
{
//MessageBox("打开exe资源文件出错");
return;
}
LARGE_INTEGER li;
// li.QuadPart = 50;
// SetFilePointerEx(handle, li,NULL, FILE_END);
li.QuadPart = FindEndOfPE();
SetFilePointerEx(handle, li, NULL, FILE_BEGIN);
#ifdef TCHAR
TCHAR string[8];
wcscpy(string, "TTTTTTT");
#else
char string[256];
strcpy(string, _strMsg.GetBuffer(_strMsg.GetLength()));
#endif
DWORD dwnumToWrite = 0;
WriteFile(handle, string, strlen(string), &dwnumToWrite, NULL);
CloseHandle(handle);
}