How to get the total available disk space on Posix systems?

I am writing a cross-platform application and I need the full available disk space. For posix systems (Linux and Macos) I use 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 get pretty strange values ​​that I cannot understand. For example: f_blocks = 73242188 f_bsize = 1048576 f_bfree = 50393643 ...

Are these values ​​bits, bytes, or something else? I read here about stackoverflow, which should be bytes, but then I would get the total number of free bytes: f_bsize * f_bfree = 1048576 * 50393643 but that means 49212.542GB ... too much ...

Am I doing something with code or something else? Thank!

+5
4

, . statvfs statfs. 4096, , . !

+2

OSX , , , , , f_blocks f_bfree " " "" ( buf.f_frsize ) " " ( buf.f_bsize bytes):

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

f_bsize - , -, .

+8

:

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

HD.

I also got strange results, until I realized that my HD 455GiB, please consider splitting blocks, blksize and freeblks vars into unsigned long before multiplication.

Something like that:

unsigned long long disk_size = (unsigned long long) (blocks) * (unsigned long long) (blksize)

I have seen many such questions, but no one has noticed this in the answers.

+3
source
uint64_t userAvailableFreeSpace()
{
    struct statvfs stat;
    struct passwd *pw = getpwuid(getuid());
    if ( NULL != pw && 0 == statvfs(pw->pw_dir, &stat) )
    {
        uint64_t freeBytes = (uint64_t)stat.f_bavail * stat.f_frsize;
        return freeBytes;
    }
    return 0ULL;
}
+1
source

All Articles