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

I need to create a huge binary file filled with zeros on Windows. Its size is set. What is the most efficient way to do this in C / C ++?

+6
source share
5 answers

Try calling truncate(2) :

 truncate("/my/file", my_size); 

For more information

 man 2 truncate 

The truncate () and ftruncate () functions cause a regular file named path or fd to be truncated to exactly the size of bytes.

If the file was previously larger than this size, additional data is lost. If the file was previously shorter, it is expanded, and the extended part is read as zero bytes ('\ 0').

If you are looking for a native Windows function, look at SetEndOfFile , which does the same thing.

+6
source

If the file really needs to be all zeros, then there is no other way but to write all the data. I would probably do this using a buffer of the same size as the disk block size, and write it in a loop until you type the size you want.

If the file may contain "holes" where the data is undefined (which is actually already on the disk), you can search for the specified size and write one byte.

+5
source

"Fastest" is platform dependent. On unix, use open and writable system calls; Be sure to call the record with a large buffer (~ 1 MB).

+1
source

If someone wonders how I solved my problem here:

 void CreateBlankFile(LPSTR str, long lsize) { DWORD dwErr; HANDLE file = CreateFile(str, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); dwErr = GetLastError(); if (dwErr > 0) { //some error message should be here return; } SetFilePointer(file, lsize, 0, FILE_BEGIN); SetEndOfFile(file); CloseHandle(file); } 
+1
source

Perhaps this is what you are looking for, SPARSE file. These types of files are usually created using file sharing programs ...

http://www.flexhex.com/docs/articles/sparse-files.phtml

0
source

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


All Articles