4

我想使用 Windows C/C++ API 创建一个任意大小的文件。我正在使用具有 32 位虚拟地址内存空间的 Windows XP Service Pack 2。我熟悉 CreateFile。

但是 CreateFile 没有大小参数,我想传入大小参数的原因是允许我创建内存映射文件,允许用户访问预定大小的数据结构。您能否建议适当的 Windows C/C++ API 函数,它允许我创建任意预定大小的文件?谢谢

4

5 回答 5

8

CreateFile像往常一样,SetFilePointerEx到所需的大小,然后调用SetEndOfFile.

于 2011-01-20T20:56:09.670 回答
2

您不需要文件,您可以使用页面文件作为内存映射文件的支持,来自 MSDNCreateFileMapping功能页面:

如果 hFile 为 INVALID_HANDLE_VALUE,调用进程还必须在 dwMaximumSizeHigh 和 dwMaximumSizeLow 参数中指定文件映射对象的大小。在这种情况下,CreateFileMapping 创建一个指定大小的文件映射对象,该对象由系统分页文件支持,而不是由文件系统中的文件支持。

您仍然可以使用DuplicateHandle.

于 2011-01-20T21:03:35.320 回答
2

要在 UNIX 上执行此操作,请查找 (RequiredFileSize - 1),然后写入一个字节。字节的值可以是任何值,但零是显而易见的选择。

于 2011-01-20T21:37:03.507 回答
1

根据您的评论,您实际上需要跨平台解决方案,因此请查看Boost Interprocess library。它提供跨平台共享内存设施等

于 2011-01-20T22:10:55.660 回答
0

要在 Linux 上执行此操作,您可以执行以下操作:

/**
 *  Clear the umask permissions so we 
 *  have full control of the file creation (see man umask on Linux)
 */
mode_t origMask = umask(0);

int fd = open("/tmp/file_name",
      O_RDWR, 00666);

umask(origMask);
if (fd < 0)
{
  perror("open fd failed");
  return;
}


if (ftruncate(fd, size) == 0)
{
   int result = lseek(data->shmmStatsDataFd, size - 1, SEEK_SET);
   if (result == -1)
   {
     perror("lseek fd failed");
     close(fd);
     return ;
   }

   /* Something needs to be written at the end of the file to
    * have the file actually have the new size.
    * Just writing an empty string at the current file position will do.
    *newDataSize
    * Note:
    *  - The current position in the file is at the end of the stretched
    *    file due to the call to lseek().
    *  - An empty string is actually a single '\0' character, so a zero-byte
    *    will be written at the last byte of the file.
    */
   result = data->write(fd, "", 1);
   if (result != 1)
   {
     perror("write fd failed");
     close(fd);

     return;
   }
}
于 2015-08-13T17:53:14.010 回答