Creating an arbitrary file size using the Windows C ++ API

I would like to create a file of arbitrary size using the Windows C / C ++ API. I am using Windows XP Service Pack 2 (SP2) with 32-bit virtual address memory. I am familiar with CreateFile.

However, CreateFile has no size. The reason I want to pass a size argument is to allow me to create memory mapping files that allow the user to access data structures with a given size. Could you advise the correct Windows C / C ++ API function that allows me to create a file of arbitrary predefined size? Thanks you

+3
source share
5 answers

To do this on UNIX, find (RequiredFileSize - 1), and then write a byte. The byte value can be anything, but null is the obvious choice.

+2
source

You, CreateFileas usual, SetFilePointerExto the right size, and then call SetEndOfFile.

+8
source

, MSDN CreateFileMapping:

hFile INVALID_HANDLE_VALUE, dwMaximumSizeHigh dwMaximumSizeLow. CreateFileMapping , , .

DuplicateHandle.

+2

according to your comments, you really need a cross-platform solution, so check out the Boost Interprocess library . it provides cross-platform shared memory tools and more

+1
source

To do this on Linux, you can do the following:

/**
 *  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;
   }
}
0
source

Source: https://habr.com/ru/post/1786772/


All Articles