Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the fastest way to create 1GB file filled with zeros in C/C++?

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++?

like image 885
Tae-Sung Shin Avatar asked Mar 21 '12 17:03

Tae-Sung Shin


2 Answers

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.

like image 121
Steven Schlansker Avatar answered Nov 02 '22 00:11

Steven Schlansker


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.

like image 6
Some programmer dude Avatar answered Nov 01 '22 23:11

Some programmer dude