What I am trying to do is to write a C program on linux which should be checking in the current directory if there are sparse files, and also I would like to print the number of disk blocks that already represent gaps in the file and the number of disk blocks that are 0-filled but take up disk space.
So far I can access the current directory and print just the files with
DIR *dirp;
struct dirent *dp;
To get done the second part with sparse file I tried to use stat() but it seems not to be working because I don't get the required results as I wished.
So, could anyone show me how to do the part with the sparse file?
If you want to look for holes in sparse files, see the manpage for lseek, specifically the bit concerning SEEK_HOLE and SEEK_DATA.
If you want to just know the allocated size on disk, then look at then manpage for stat (2):
struct stat {
...
off_t st_size; /* total size, in bytes */
...
blksize_t st_blksize; /* blocksize for file system I/O */
blkcnt_t st_blocks; /* number of 512B blocks allocated */
};
st_size tells you the total size in bytes, st_blksize * st_blocks gives you the allocated size. If you round st_size up to the next multiple of st_blksize and subtract the file size, that's the size of the holes.
You can try the following trick with stat result:
if (st.st_blocks * st.st_blksize < st.st_size) {
SPARSE-FILE
} else {
PROBABLY NOT SPARSE
}
Not sure if it identifies all sparse files however.