如何获得 Posix 系统中的总可用磁盘空间? [英] How to obtain total available disk space in Posix systems?
问题描述
我正在编写一个跨平台的应用程序,我需要可用的总磁盘空间.对于 posix 系统(Linux 和 Macos),我使用的是 statvfs.我创建了这个 C++ 方法:
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;
}
}
不幸的是,我得到了一些我无法理解的奇怪值.例如:f_blocks = 73242188f_bsize = 1048576f_bfree = 50393643...
Unfortunately I'm getting quite strange values I can't understand. For instance: f_blocks = 73242188 f_bsize = 1048576 f_bfree = 50393643 ...
这些值是以位、字节还是其他形式表示的?我在stackoverflow上读到这些应该是字节,但是我得到的可用字节总数是:f_bsize*f_bfree = 1048576*50393643但这意味着 49212.542GB...太多...
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!
推荐答案
我认为最后两个答案是正确且有用的.但是我通过简单地将函数 statvfs 替换为函数 statfs 来解决.块大小是预期的 4096,一切似乎都是正确的.谢谢!
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!
这篇关于如何获得 Posix 系统中的总可用磁盘空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!