在Linux环境下,使用C语言获取文件夹大小涉及到文件系统的遍历和文件属性的读取。以下是一个基本的示例代码,展示了如何实现这一功能:
#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
long long get_directory_size(const char *dir_path) {
DIR *dir;
struct dirent *entry;
struct stat statbuf;
long long total_size = 0;
if ((dir = opendir(dir_path)) == NULL) {
perror("opendir");
return -1;
}
while ((entry = readdir(dir)) != NULL) {
char path[1024];
snprintf(path, sizeof(path), "%s/%s", dir_path, entry->d_name);
if (stat(path, &statbuf) == -1) {
perror("stat");
continue;
}
if (S_ISDIR(statbuf.st_mode)) {
if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
long long subdir_size = get_directory_size(path);
if (subdir_size == -1) {
continue;
}
total_size += subdir_size;
}
} else {
total_size += statbuf.st_size;
}
}
closedir(dir);
return total_size;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return 1;
}
long long size = get_directory_size(argv[1]);
if (size == -1) {
fprintf(stderr, "Failed to get directory size.\n");
return 1;
}
printf("Total size of '%s': %lld bytes\n", argv[1], size);
return 0;
}
stat
系统调用获取文件的元数据,如大小、权限等。stat
调用会失败。可以通过检查errno
来确定具体错误并相应处理。S_ISLNK
并跳过符号链接来解决。通过上述代码和方法,可以在Linux环境下有效地获取文件夹的大小。
领取专属 10元无门槛券
手把手带您无忧上云