1

我在 Windows 平台上映射了一个未知大小(大约 4-6 GiB)的文件,并获得了一个指向从 MapFileView 函数返回的文件数据开始的指针。但是当我使用指针顺序访问数据时,我怎么知道我已经到达文件的末尾呢?

这是我到目前为止编写的代码,它成功地映射了文件并返回了指针:

    #include <Windows.h>
    #include <stdio.h>
    #include <inttypes.h>

    int main()
    {
      HANDLE hFile = CreateFile("Test.bin",
                                 GENERIC_READ | GENERIC_WRITE,
                                 0,
                                 NULL,
                                 OPEN_EXISTING,
                                 FILE_ATTRIBUTE_NORMAL,
                                 NULL);
      if (!hFile)
      {
        printf("Could not create file (%lu).\n", GetLastError());
        exit(1) ;
      }

      HANDLE hMapFile = CreateFileMappingA(hFile,
                                           NULL,
                                           PAGE_READWRITE,
                                           0,
                                           0,
                                           NULL);
      if (!hMapFile)
      {
        printf("Could not create file mapping object (%lu).\n", GetLastError());
        CloseHandle(hFile);
        exit(1);
      }

      int32_t* pBuf = (int32_t*) MapViewOfFile(hMapFile,
                                               FILE_MAP_ALL_ACCESS,
                                               0,
                                               0,
                                               0);
      if (!pBuf)
      {
        printf("Could not map file (%lu).\n", GetLastError());
        CloseHandle(hFile);
        CloseHandle(hMapFile);
        exit(1);
      };

      UnmapViewOfFile(pBuf);
      CloseHandle(hFile);
      CloseHandle(hMapFile);

      exit(0);
    }

所以我想在多个线程中同时读取文件大小相同的不同部分。我相信映射文件是为此目的的正确选择。高度赞赏有关任何其他更快和可能的方法的建议。

我在论坛中研究了一些类似的问题,我想这是我能找到的最接近的主题: Read all contents of memory mapped file or Memory Mapped View Accessor without known the size 但是这个答案是使用 C# 编写的,而不是使用WinAPI,因此,我无法理解他们的过程。

提前致谢 :)

4

1 回答 1

1

调用GetFileSizeEx以获取文件的大小,并将其与基地址和当前读取地址结合使用来确定结束地址在哪里。

于 2020-02-12T15:31:19.807 回答