Advertisement
AyrA

Sparse file creation

Nov 15th, 2015
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <time.h>
  3.  
  4. void createSparse(const char*,const long);
  5.  
  6. int main()
  7. {
  8.     /*to measure time*/
  9.     clock_t begin,end;
  10.     printf("Writing sparse file (1G) now...\n");
  11.     begin=clock();
  12.     createSparse("test.bin",1024*1024*1024);
  13.     end=clock();
  14.     /*tell how long it took*/
  15.     printf("Done in %i ms\n",(int)((end-begin)*1000/CLOCKS_PER_SEC));
  16.     return 0;
  17. }
  18.  
  19. /*creates a sparse file of specified length*/
  20. void createSparse(const char* Filename,const long len)
  21. {
  22.     FILE* fp;
  23.     remove(Filename);
  24.     if((fp=fopen(Filename,"wb")))
  25.     {
  26.         /*
  27.             The magic lies in the next two lines.
  28.             If the filesystem supports sparse files, this will complete almost instantly.
  29.             If the filesystem does not supports sparse files, this will properly zero the whole file.
  30.         */
  31.         fseek(fp,len-1,SEEK_SET);
  32.         fwrite("",1,1,fp);
  33.         fclose(fp);
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement