linux

如何使用readdir统计文件数量

小樊
42
2025-06-05 23:49:08
栏目: 编程语言

readdir 是一个用于读取目录内容的函数,通常在 C 或 C++ 语言中使用。要使用 readdir 统计文件数量,你需要遍历目录中的所有条目,并检查每个条目是否为文件。以下是一个使用 readdir 统计文件数量的示例:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Usage: %s <directory_path>\n", argv[0]);
        return 1;
    }

    DIR *dir = opendir(argv[1]);
    if (dir == NULL) {
        perror("opendir");
        return 1;
    }

    struct dirent *entry;
    int file_count = 0;

    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录(.)和上级目录(..)
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 使用 stat 函数获取文件信息
        struct stat file_stat;
        if (stat(argv[1] "/" entry->d_name, &file_stat) == 0) {
            // 检查是否为文件
            if (S_ISREG(file_stat.st_mode)) {
                file_count++;
            }
        }
    }

    closedir(dir);

    printf("Number of files: %d\n", file_count);
    return 0;
}

这个程序接受一个目录路径作为命令行参数,然后使用 readdir 函数遍历目录中的所有条目。对于每个条目,我们使用 stat 函数获取文件信息,并检查它是否为普通文件(而不是目录、符号链接等)。最后,我们输出文件数量。

要编译此程序,请使用以下命令:

gcc -o count_files count_files.c

然后运行程序,传递一个目录路径作为参数:

./count_files /path/to/directory

0
看了该问题的人还看了