AyrA icon

Sparse file creation

AyrA | PRO | 11/15/15 10:21:47 PM UTC | 0 ⭐ | 505 👁️ | Never ⏰ | []
C |

830 B

|

None

|

0 👍

/

0 👎

#include <stdio.h>
#include <time.h>
 
void createSparse(const char*,const long);
 
int main()
{
    /*to measure time*/
    clock_t begin,end;
    printf("Writing sparse file (1G) now...\n");
    begin=clock();
    createSparse("test.bin",1024*1024*1024);
    end=clock();
    /*tell how long it took*/
    printf("Done in %i ms\n",(int)((end-begin)*1000/CLOCKS_PER_SEC));
    return 0;
}
 
/*creates a sparse file of specified length*/
void createSparse(const char* Filename,const long len)
{
    FILE* fp;
    remove(Filename);
    if((fp=fopen(Filename,"wb")))
    {
        /*
            The magic lies in the next two lines.
            If the filesystem supports sparse files, this will complete almost instantly.
            If the filesystem does not supports sparse files, this will properly zero the whole file.
        */
        fseek(fp,len-1,SEEK_SET);
        fwrite("",1,1,fp);
        fclose(fp);
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎