Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

432
Views
C - Linux Sparse File: How to check if file is sparse and print 0-filled disk blocks

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

Check size, returned by du utility, and compare with the "apparent size". If you wish you may take a look on the block counting algorithm from du

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!