Skip to content
Advertisement

How to obtain total available disk space in Posix systems?

I’m writing a cross-platform application, and I need the total available disk space. For posix systems (Linux and Macos) I’m using statvfs. I created this C++ method:

long OSSpecificPosix::getFreeDiskSpace(const char* absoluteFilePath) {
   struct statvfs buf;

   if (!statvfs(absoluteFilePath, &buf)) {
      unsigned long blksize, blocks, freeblks, disk_size, used, free;
      blksize = buf.f_bsize;
      blocks = buf.f_blocks;
      freeblks = buf.f_bfree;

      disk_size = blocks*blksize;
      free = freeblks*blksize;
      used = disk_size - free;

      return free;
   }
   else {
      return -1;
   }
}

Unfortunately I’m getting quite strange values I can’t understand. For instance: f_blocks = 73242188 f_bsize = 1048576 f_bfree = 50393643 …

Are those values in bits, bytes or anything else? I read here on stackoverflow those should be bytes, but then I would get the total number of bytes free is: f_bsize*f_bfree = 1048576*50393643 but this means 49212.542GB… too much…

Am I doing something wrong with the code or anything else? Thanks!

Advertisement

Answer

I suppose the last two answers are correct and useful. However I solved by simply replacing the function statvfs with the function statfs. The block size is then 4096 as expected and everything seems to be correct. Thanks!

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement