linux下编写一个函数,计算目录下总文件大小
使用 POSIX 标准库中的系统调用来实现计算目录下所有文件的大小。
#include <iostream>
#include <dirent.h>
#include <sys/stat.h>
// 递归计算目录下所有文件的大小
std::uintmax_t calculateDirectorySize(const std::string& directoryPath)
{
std::uintmax_t totalSize = 0;
DIR* dir = opendir(directoryPath.c_str());
if (dir == nullptr)
{
std::cerr << "Failed to open directory: " << directoryPath << std::endl;
return 0;
}
struct dirent* entry;
while ((entry = readdir(dir)) != nullptr)
{
std::string entryName = entry->d_name;
if (entryName != "." && entryName != "..") // 过滤两个特殊目录项
{
std::string entryPath = directoryPath + "/" + entryName;
struct stat st;
if (stat(entryPath.c_str(), &st) == 0) // 如果 stat 函数成功执行并获取了文件信息,它会返回 0
{
if (S_ISDIR(st.st_mode))
Linux下计算目录总文件大小的函数实现

最低0.47元/天 解锁文章
8905

被折叠的 条评论
为什么被折叠?



