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

Mat*_*att 45 c++ linux

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

Joh*_*ter 86

校验 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 */
           };
Run Code Online (Sandbox Code Playgroud)

  • 使用`f_bsize*f_bavail`使数据与`df -h`命令一致. (7认同)
  • statvfs似乎不适用于vfat安装的驱动器.我尝试使用FAT 32分区,它为可用块提供0.有办法解决这个问题吗? (5认同)
  • 这看起来正是我需要的。干杯! (2认同)
  • @ShadmanAnwer 不幸的是,手册页说:`返回结构的所有成员是否在所有文件系统上都具有有意义的值是不确定的。`所以在这种情况下可能不支持 FAT32。 (2认同)
  • f_bfree和f_bavail之间的区别是由于为超级用户(ext2/3/4文件系统)保留的块.默认为磁盘的5%.它可以使用`tune2fs`进行更改,选项为`-r <count>`或`-m <percentage>`.它也可以在文件系统创建期间设置. (2认同)

San*_*eep 30

你可以使用boost :: filesystem:

struct space_info  // returned by space function
{
    uintmax_t capacity;
    uintmax_t free; 
    uintmax_t available; // free space available to a non-privileged process
};

space_info   space(const path& p);
space_info   space(const path& p, system::error_code& ec);
Run Code Online (Sandbox Code Playgroud)

例:

#include <boost/filesystem.hpp>
using namespace boost::filesystem;
space_info si = space(".");
cout << si.available << endl;
Run Code Online (Sandbox Code Playgroud)

返回:类型为space_info的对象.space_info对象的值确定为使用POSIX statvfs()获取POSIX结构statvfs,然后将其f_blocks,f_bfree和f_bavail成员乘以其f_frsize成员,并将结果分配给容量,free和可用会员分别.任何无法确定其值的成员都应设置为-1.


Elm*_*mar 16

使用 C++17

您可以使用std::filesystem::space

#include <iostream>  // only needed for screen output

#include <filesystem>
namespace fs = std::filesystem;

int main()
{
    fs::space_info tmp = fs::space("/tmp");

    std::cout << "Free space: " << tmp.free << '\n'
              << "Available space: " << tmp.available << '\n';
}
Run Code Online (Sandbox Code Playgroud)