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

但是,CreateFile没有尺寸的凸起,我要传递大小参数的原因是允许我创建内存映射文件,以允许用户访问预定大小的数据结构。您能否请建议正确的Windows C/C ++ API函数,这使我可以创建一个预定尺寸的文件?谢谢

有帮助吗?

解决方案

要在Unix上执行此操作,请寻求(必需filesize -1),然后编写一个字节。字节的价值可以是任何东西,但是零是明显的选择。

其他提示

CreateFile 照常, SetFilePointerEx 到所需的尺寸,然后致电 SetEndOfFile.

您不需要文件,可以将pageFile用作内存映射文件的备份,从MSDN CreateFileMapping 功能页面:

如果HFILE是Invalid_handle_value,则调用过程还必须在dwmaximumsizehigh和dwmaximumsizelow参数中指定文件映射对象的大小。在这种情况下,CreateFileMapping创建了一个由系统编写文件支持的指定大小的文件映射对象,而不是文件系统中的文件。

您仍然可以通过使用 DuplicateHandle.

根据您的评论,您实际上需要跨平台解决方案,因此请检查 提升分解 图书馆。它提供跨平台共享内存设施和更多

要在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;
   }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top