Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 701
Luca Carlon Avatar asked Oct 10 '10 10:10

Luca Carlon


People also ask

Which command displays the amount of free disk space?

Use the df command to show the amount of free disk space on each mounted disk. The usable disk space that is reported by df reflects only 90 percent of full capacity, as the reporting statistics allows for 10 percent above the total available space.

How do I check disk space on Ubuntu?

To check the free disk space and disk capacity with System Monitor: Open the System Monitor application from the Activities overview. Select the File Systems tab to view the system's partitions and disk space usage. The information is displayed according to Total, Free, Available and Used.


1 Answers

I don't know OSX well enough to predict this is definitely the answer, but f_blocks and f_bfree actually refer to "fundamental blocks", or "fragments" (which are of size buf.f_frsize bytes), not the "filesystem block size" (which is buf.f_bsize bytes):

http://www.opengroup.org/onlinepubs/009695399/basedefs/sys/statvfs.h.html

f_bsize is just a hint what the preferred size is for I/O operations, it's not necessarily anything to do with how the filesystem is divided.

like image 78
Steve Jessop Avatar answered Oct 31 '22 14:10

Steve Jessop