在 Debian(或者说 Linux 下),readdir 本身是 C 语言里读取目录项的函数(readdir() / readdir_r()),它本身不会自动统计文件数,需要你在代码里自己计数。
下面分几种常见情况说明。
readdir 统计文件数(最贴近你的问题). 和 ..)#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
int count = 0;
dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
count++;
}
closedir(dir);
printf("Total entries: %d\n", count);
return 0;
}
. 、..)#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
struct stat st;
char path[1024];
int count = 0;
dir = opendir(argv[1]);
if (!dir) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
stat(path, &st);
if (S_ISREG(st.st_mode)) // 普通文件
count++;
}
closedir(dir);
printf("Regular files: %d\n", count);
return 0;
}
find)思路:
readdir 发现目录如果你需要,我可以给你一份完整递归版本。
如果你只是想“统计文件数”,通常更快:
ls -1 | wc -l
find . -maxdepth 1 -type f | wc -l
find . -type f | wc -l
readdir 只是“读目录”find 通常比写 C 更方便如果你能告诉我:
我可以直接给你最合适的完整代码。