如何以编程方式获取 Linux 中目录的可用磁盘空间

新手上路,请多包涵

是否有一个函数可以返回给定目录路径的驱动器分区上有多少可用空间?

原文由 hookenz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 804
2 个回答

检查 man statvfs(2)

我相信您可以将“可用空间”计算为 f_bsize * f_bfree

 NAME
       statvfs, fstatvfs - get file system statistics

SYNOPSIS
       #include <sys/statvfs.h>

       int statvfs(const char *path, struct statvfs *buf);
       int fstatvfs(int fd, struct statvfs *buf);

DESCRIPTION
       The function statvfs() returns information about a mounted file system.
       path is the pathname of any file within the mounted file  system.   buf
       is a pointer to a statvfs structure defined approximately as follows:

           struct statvfs {
               unsigned long  f_bsize;    /* file system block size */
               unsigned long  f_frsize;   /* fragment size */
               fsblkcnt_t     f_blocks;   /* size of fs in f_frsize units */
               fsblkcnt_t     f_bfree;    /* # free blocks */
               fsblkcnt_t     f_bavail;   /* # free blocks for unprivileged users */
               fsfilcnt_t     f_files;    /* # inodes */
               fsfilcnt_t     f_ffree;    /* # free inodes */
               fsfilcnt_t     f_favail;   /* # free inodes for unprivileged users */
               unsigned long  f_fsid;     /* file system ID */
               unsigned long  f_flag;     /* mount flags */
               unsigned long  f_namemax;  /* maximum filename length */
           };

原文由 John Ledbetter 发布,翻译遵循 CC BY-SA 2.5 许可协议

您可以使用 Qt 类 QStorageInfo 来获取硬盘空闲空间:首先,您应该包含标题:

 #include <QStorageInfo>
#define GB (1024 * 1024 * 1024)
bool CheckHardiskFree(const QString &strDisk)
{
    QStorageInfo storage(strDisk);
    if(storage.isValid() && storage.isReady())
    {
     double useGb =(storage.bytesTotal()-storage.bytesAvailable()) * 1.0/ GB;
     double freeGb =storage.bytesAvailable() * 1.0 / GB;
     double allGb =storage.bytesTotal()* 1.0 / GB;
     return true;
    }
    return false;
}

原文由 KennyAckerman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题