linux统计目录下文件大小 c语言
时间: 2023-07-26 11:32:24 浏览: 57
你可以使用C语言中的系统调用函数来实现统计目录下文件大小的功能。下面是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
exit(1);
}
DIR *dir = opendir(argv[1]);
if (dir == NULL) {
perror("opendir");
exit(1);
}
struct dirent *entry;
struct stat st;
long long total_size = 0;
while ((entry = readdir(dir)) != NULL) {
char path[1024];
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &st) == -1) {
perror("stat");
continue;
}
if (S_ISREG(st.st_mode)) {
total_size += st.st_size;
}
}
closedir(dir);
printf("Total size of regular files in %s: %lld bytes\n", argv[1], total_size);
return 0;
}
```
这个程序会计算指定目录下所有普通文件的大小之和,并打印出结果。注意,程序中使用了标准库函数 `snprintf` 来构造文件路径,防止了路径溢出问题。同时,使用 `S_ISREG` 宏来判断文件是否为普通文件,避免了其他类型文件对计算结果的影响。