在 CentOS(Linux) 下,如果你想用 readdir(通常是 C 语言 opendir / readdir)来“计数”,一般指的是:
下面按常见场景说明。
readdir 计数(最标准). 和 ..)#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
int count = 0;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
while ((entry = readdir(dir)) != NULL) {
count++;
}
closedir(dir);
printf("总条目数: %d\n", count);
return 0;
}
. 和 ..while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
count++;
}
#include <sys/stat.h>
struct stat st;
char path[256];
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "%s/%s", ".", entry->d_name);
if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
count++;
}
}
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
count++;
}
如果你不是写 C 程序,而是 在 CentOS 上直接统计目录数量:
ls -1 | wc -l
ls -1a | wc -l
find . -maxdepth 1 -type f | wc -l
find . -maxdepth 1 -type d | wc -l
readdir 是 逐条读取目录项stat 更慢stat| 需求 | 方法 |
|---|---|
| C 语言计数 | opendir + readdir |
排除 . .. |
strcmp |
| 区分文件/目录 | stat |
| Shell 快速统计 | find / ls |
如果你能说明:
我可以给你更精确的代码。