Search code examples
clinuxdiskspaceodroid

Available(Free) Disk Space in Linux shows negative?


#include <sys/statvfs.h>

int GET_DISK_SPACE()
{
  struct statvfs sbuf;
  statvfs("/home/odroid", &sbuf);
  printf("Bytes left:%ld\n", sbuf.f_frsize*sbuf.f_bavail);

}

Wrote this simple function to get disk space on my linux machine and it returns negative value. original: -89366528

Then I added a simple text file with Size: 877 bytes | Size on disk: 4.00 KB

and the value changed to -89370624

Then duplicated the file and got -89374720 These numbers don't make any sense. Not sure what I'm doing wrong. When I run df -h this is what I get

enter image description here


Solution

  • To be sure that you aren't experiencing arithmetic overflow, and don't have a format string mismatch, use long long explicitly:

    unsigned long long num_bytes = sbuf.f_bsize;
    num_bytes *= sbuf.f_bavail;
    printf("Bytes available: %llu\n", num_bytes);
    

    As long as your expression's type is dependent on the structure member types, which are typedefs, it will be impossible to pick the correct format string. Since printf is varargs, the compiler won't automatically convert to the correct type. Introducing a helper variable allows you to be absolutely sure of the width of the parameter passed to printf.

    Also, check the return value from statvfs to make sure these values actually mean something. If you got an error, they won't be good for anything.