在 Linux 下,使用 readdir 统计目录中文件(或条目)数量,通常的做法是:
循环调用 readdir,对返回的每一个目录项进行计数。
下面分别给出 C 语言示例 和 Shell 命令方式。
. 和 ..)#include <stdio.h>
#include <dirent.h>
int main(int argc, char *argv[]) {
DIR *dir;
struct dirent *entry;
int count = 0;
if (argc < 2) {
printf("Usage: %s <dir>\n", argv[0]);
return 1;
}
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;
}
. 和 ..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[1024];
while ((entry = readdir(dir)) != NULL) {
snprintf(path, sizeof(path), "%s/%s", argv[1], entry->d_name);
if (stat(path, &st) == 0 && S_ISREG(st.st_mode)) {
count++;
}
}
# 统计当前目录文件数(不含 . 和 ..)
ls -1 | wc -l
# 包括隐藏文件
ls -1a | wc -l
# 只统计普通文件
find . -maxdepth 1 -type f | wc -l
readdir 不会递归子目录readdir 返回的是目录项,不是文件内容如果你需要:
可以告诉我你的具体场景。