2

Is there an equivalent to posix_fallocate() on windows? Specifically, I'm looking for a way to instantly (without performing a ton of IO) create a file of a particular size (I don't care about the contents). I have tried _chsize_s() which does allocate the file but it takes a long time and if I right click on the file and choose properties I can see that its increasing in size... so it appears to be writing to it.

dicroce
  • 45,396
  • 28
  • 101
  • 140
  • 1
    `CreateFileW` + `SetFileInformationByHandle` with `FileEndOfFileInfo` – RbMm Mar 27 '22 at 13:30
  • 1
    Or `SetFilePointer` + `SetEndOfFile`. Note that for security reasons, the extended file data will be zeroed out on demand, so if you seek to near the end and then write a byte, then you will incur a lot of I/O as the system zero-fills all the intermediate bytes. There is also SetFileValidData which leaves the intermediate bytes uninitialized, but that comes with security implications (information disclosure of previous volume contents). – Raymond Chen Mar 27 '22 at 13:37
  • NTFS has support for [sparse files](https://learn.microsoft.com/en-us/windows/win32/fileio/sparse-files). Though I'm curious as to why anyone would ever want to limit themselves to what POSIX supports. I mean, that's literally a race to the bottom. What's the *specific* problem you are trying to solve? – IInspectable Mar 27 '22 at 15:12
  • This question seems to want the opposite of what `posix_fallocate()` does, as that function does preallocates the space on the storage, which can take a long time with a lot of IO, depending on how it was implemented on the POSIX system. – lvella Jun 10 '23 at 15:09

1 Answers1

0

To summarize all the comments:

You may want to create a sparse file, which can have ranges that are not allocated on storage that reads as zero, so it is very fast to resize to any size.

See this answer for how to create it. Once you have a file set as sparse, you can set its size with SetFilePointer() + SetEndOfFile(), which should return immediately, as the file is sparse.

That said, these have almost the opposite effect of posix_fallocate(), which takes a file full of sparse holes and do whatever IO necessary to ensure the file is fully allocated on the storage and filled with zeros, so that no writes fails. This operation is potentially slow, depending on how it is implemented by the POSIX system, and apparently not what you want.

lvella
  • 12,754
  • 11
  • 54
  • 106