【发布时间】:2011-04-28 21:01:20
【问题描述】:
是否有一个函数可以返回给定目录路径的驱动器分区上有多少可用空间?
【问题讨论】:
是否有一个函数可以返回给定目录路径的驱动器分区上有多少可用空间?
【问题讨论】:
查看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 */
};
【讨论】:
It is unspecified whether all members of the returned struct have meaningful values on all file systems. 所以在这种情况下可能不支持 FAT32。
f_bsize * f_bavail 使数据与df -h 命令一致。
tune2fs 和选项 -r <count> 或 -m <percentage> 更改它。也可以在文件系统创建过程中设置。
你可以使用 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);
例子:
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
space_info si = space(".");
cout << si.available << endl;
返回:space_info 类型的对象。 space_info 对象的值是通过使用 POSIX statvfs() 获得一个 POSIX struct statvfs,然后将其 f_blocks、f_bfree 和 f_bavail 成员乘以其 f_frsize 成员来确定的,并将结果分配给 capacity、free 和分别可用的成员。任何无法确定其值的成员都应设置为-1。
【讨论】:
你可以使用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';
}
【讨论】:
-lstdc++fs。见注释here
可以使用这样的管道将命令的输出输入到程序中:
char cmd[]="df -h /path/to/directory" ;
FILE* apipe = popen(cmd, "r");
// if the popen succeeds read the commands output into the program with
while ( fgets( line, 132 , apipe) )
{ // handle the readed lines
}
pclose(apipe);
// -----------------------------------
【讨论】: