一、简介
boost::filesystem可以进行跨平台的文件操作,Linux下statfs可以获取挂载点的文件系统信息(Windows下要用windows的API)。
二、代码如下
#include<iostream>
#include <string>
#include <vector>
#include <sys/statfs.h>
#include <errno.h>
#include <boost/filesystem.hpp>
using namespace std;
int main()
{
boost::system::error_code ec;
boost::filesystem::directory_iterator end_iter;//非递归
vector<string> dirs;
for (boost::filesystem::directory_iterator iter("/"); iter != end_iter; iter++)
{
if (boost::filesystem::is_directory(*iter, ec))
{
dirs.push_back(iter->path().string());
}
}
for (const auto &disk_partition : dirs)
{
cout << disk_partition;
struct statfs statbuf = { 0 };
if (statfs(disk_partition.c_str(), &statbuf) >= 0)
{
unsigned long long free_space = (unsigned long long)((unsigned long long)statbuf.f_bavail * (unsigned long long)statbuf.f_bsize);
unsigned long long total_space = (unsigned long long)((unsigned long long)statbuf.f_blocks * (unsigned long long)statbuf.f_bsize);
std::cout << " free space is " << free_space / 1024 / 1024 << "M";
std::cout << " total space is " << total_space / 1024 / 1024 << "M" << endl;
}
else
{
cout << "statfs is error!error code is " << errno << endl;
}
}
return 0;
}
三、编译
注意自行搞定boost的库目录
g++ hello.cpp -o hello -Iboost-V1.67.0/include/ -Lboost-V1.67.0/bin/ -lboost_filesystem -lboost_system -Wl,-rpath='$ORIGIN' -std=c++11
四、运行结果如下