怎样用C++内存映射磁盘文件的方式映射一个几百M的文件,还有几十M,还有几十K的文件?

2025-04-06 18:41:44
推荐回答(1个)
回答1:

#include 
#include
#include
int main()
{
    HANDLE hFile = CreateFile(_T("1.txt"), GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
    if (hFile == INVALID_HANDLE_VALUE) {
        puts("fail to create file");
        goto fail_open;
    }
       
    SetFileValidData(hFile, 1024);
       
    HANDLE hMap = CreateFileMapping(hFile, 0, PAGE_READWRITE, 0, 1024, 0);
    if (hMap == NULL) {
        puts("fail to create mapping");
        goto fail_map;
    }
       
    LPVOID pContent = MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 1024);
    if (pContent == 0) {
        puts("fail to open mapping");
        goto fail_view;
    }
       
    //好了,此时这个文件就相当于你用malloc申请的一个1024字节的内存空间。
    char* pStr = (char*) pContent;
    strcpy(pStr, "hahaha");
       
    UnmapViewOfFile(pContent);
    fail_view:
    CloseHandle(hMap);
    fail_map:
    CloseHandle(hFile);
    fail_open:
    return 0;
}