Question

I am trying to get the available disk space. However, the size I am getting back does not change when I write more files to disk. What am I doing wrong?

I confirmed that I am writing to /dev/sda1 by running df -h and seeing that available space is indeed going down as I write files to disk.

double size; //size of aval disk space
struct statvfs buf;

if((statvfs("/dev/sda1", &buf)) < 0)
{
   printf("Failed to get statvfs\n");
}
else
{
    size = (((double)buf.f_bavail * buf.f_bsize) / 1048576);
    printf("You have: %.0f MB free\n", size);
}
Was it helpful?

Solution

You need to call statvfs on a path that is on the mounted filesystem you want to check, e.g.

statvfs("/", &buf)

Any path on the filesystem will do, e.g. "/home/user/foo/tmp/file.txt"

statvfs on /dev/sda1 will likely report usage of the /dev filesystem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top