Wednesday 7 March 2012

Programmatically find out if a file is sparse

You can work out if a file is sparse using stat (or fstat etc).

    struct stat statbuf;
    int ret = ::stat(tmp, &tatbuf);
    ASSERT_NE(ret, -1);

    // statbuf.st_size - virtual size in bytes
    // statbuf.st_blocks - physical size in 512-byte blocks
So if st_blocks * 512 < st.size then you definitely have a sparse file.