温馨提示×

centos readdir如何计数

小樊
37
2026-10-06 02:34:29
栏目: 智能运维

在 CentOS(Linux) 下,如果你想用 readdir(通常是 C 语言 opendir / readdir)来“计数”,一般指的是:

  • 统计目录中的 文件数量
  • 或统计 某种类型的文件数量

下面按常见场景说明。


一、使用 C 语言 readdir 计数(最标准)

1️⃣ 统计目录下所有条目(包含 . 和 ..)

#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;
}

2️⃣ 排除 . 和 ..

while ((entry = readdir(dir)) != NULL) {
    if (strcmp(entry->d_name, ".") == 0 ||
        strcmp(entry->d_name, "..") == 0)
        continue;
    count++;
}

3️⃣ 只统计普通文件(排除目录)

#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++;
    }
}

4️⃣ 只统计目录

if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
    count++;
}

二、在 Shell 中“等价”的 readdir 计数(常用)

如果你不是写 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

如果你能说明:

  • 是 C 程序 还是 Shell
  • 是否需要 递归
  • 是否要 过滤文件类型

我可以给你更精确的代码。

0 踩