I need to create a huge binary file filled with zeros in Windows OS. Its size is given. What's the most efficient way to do it in C/C++?
Try calling truncate(2)
:
truncate("/my/file", my_size);
For more information,
man 2 truncate
The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.
If the file previously was larger than this size, the extra data is lost. If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
If you are looking for the Windows native function, take a look at SetEndOfFile, which does much the same thing.
If the file really need to be all zeroes, then there is no other way than to write all of the data. I would probably do it using a buffer of the same size as the drive block-size, and write it in a loop until you written to the size you want.
If the file can contain "holes" where the data is undefined (what's on the disk already really) you can seek to the specified size and write a single byte. Holes like that will actually be read as zeros.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With