c++ - 增加内存映射文件的大小

标签 c++ c windows winapi memory-mapped-files

<分区>

Possible Duplicate:
How to dynamically expand a Memory Mapped File

您好,我在 Windows 的内存映射文件中存储了一个树状数据结构,当我需要插入一条记录时,我正在检查它是否是空闲指针 更接近文件末尾。但真正的问题在于调整文件大小。

在 Windows 文档中,据说 `CreateFileMapping' 会根据其参数调整文件大小。所以我决定像下面这样使用它。

#define SEC_IMAGE_NO_EXECUTE 0x11000000

static void resize_file(wchar_t * file_name,int size)
{
  hFile = CreateFile(file_name,GENERIC_READ|GENERIC_WRITE,0,\
                     NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,\
                        NULL);
  if (hFile == INVALID_HANDLE_VALUE)
  {
       MessageBox(NULL,L"resize_file CreateFile have been failed", szAppName,MB_OK);
      exit(0);
  }

  // open file mapping object //
  HANDLE hMap = CreateFileMapping(hFile,NULL,PAGE_EXECUTE_READWRITE|SEC_IMAGE_NO_EXECUTE,0,size,NULL);

  // Close files and mapping //
  CloseHandle(hMap); 
  CloseHandle(hFile);
}

这行得通吗?我对此有点内疚,因为我只是打开并重新映射文​​件而没有刷新它。我是否需要冲洗它并进行任何其他操作?

最佳答案

documentation说两件事。

首先(在“备注”部分),

If an application specifies a size for the file mapping object that is larger than the size of the actual named file on disk and if the page protection allows write access (that is, the flProtect parameter specifies PAGE_READWRITE or PAGE_EXECUTE_READWRITE), then the file on disk is increased to match the specified size of the file mapping object. If the file is extended, the contents of the file between the old end of the file and the new end of the file are not guaranteed to be zero; the behavior is defined by the file system.

这基本上意味着当您通过调用 CreateFileMapping() 将文件映射到大于文件的内存区域时,磁盘上的文件会调整大小,并用未指定的内容填充它。

其次(在“返回值”部分),

If the object exists before the function call, the function returns a handle to the existing object (with its current size, not the specified size), and GetLastError returns ERROR_ALREADY_EXISTS.

对我来说,这意味着如果您的文件已经映射,您对 resize_file() 的调用将没有任何效果。您必须取消映射,调用 resize_file(),然后重新映射它,这可能是您想要的,也可能不是您想要的。

关于c++ - 增加内存映射文件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340059/

相关文章:

c++ - 在cmake项目中构建libgit2

c - 如何在 Eclipse CDT 应用程序中分配输入文件而不是标准输入?

c - c 中的主要函数 - 程序终止成功或失败

c - 当两个子进程都通过管道与父进程通信时,一个子进程会阻塞另一个子进程

c++ - 克里昂集成开发环境 : Use ssh as an environnent toolchains instead of MinGW/Cygwin on Windows

Windows LDAP 客户端 - 通过 CRL 启用撤销

c++ - 循环更新 Linux 的终端屏幕

c++ - 当构造函数是私有(private)的时使用公共(public)析构函数

c++ - 一个C/C++程序怎么叫没完没了?

c++ - GetSystemInfo(在 Windows 上)是否总是返回逻辑处理器的数量?