映射文件到内存

  常用代码

/*
映身文件到内存
2012-09-06 
*/

#include <windows.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
    char *cFilePath[MAX_PATH] = {""};
    HANDLE    hFileHandle, hFileMap;
    
    PIMAGE_DOS_HEADER    pDosHead;
    LPVOID pMemBase;
    char tmp[64];

    if(argv[1] == NULL)
    {
        printf("Error\n");
        return 0;
    }
    printf("自己身路径为:%s\n", argv[0]);
    strncpy(cFilePath, argv[1], MAX_PATH);
    printf("命令行路径为:%s\n", cFilePath);
    
    hFileHandle = CreateFile(cFilePath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 
                            NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
    if(hFileHandle == INVALID_HANDLE_VALUE)
    {
        printf("error\n");
        return 0;
    }
    
    hFileMap = CreateFileMapping(hFileHandle, NULL, PAGE_READWRITE, NULL, NULL, NULL);
    if(hFileMap == NULL)
    {
        printf("error\n");
        CloseHandle(hFileHandle);
        return 0;
    }
    //加载到内存的基地址 
    pMemBase = MapViewOfFile(hFileMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    
    pDosHead = (PIMAGE_DOS_HEADER)pMemBase;

    //打印基地址和PE头 
    wsprintf(tmp, "%X, %X", pMemBase, pDosHead->e_magic);
    printf("%s\n", tmp);
    
    UnmapViewOfFile(pMemBase);
    CloseHandle(hFileHandle);
    getchar();
    return 0;
}

2012-09-06

 

posted @ 2012-09-06 22:27  markro  阅读(88)  评论(0)    收藏  举报