如何使用readdir统计文件数量

如何使用readdir统计文件数量

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

#<span>include <stdio.h></span>#<span>include <stdlib.h></span>#<span>include <dirent.h></span>#<span>include <sys/stat.h></span>int main(<span>int argc, char *argv[])</span> {    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;    }    <span>struct dirent *entry;</span>    int file_count = 0;    while ((entry = readdir(dir)) != NULL) {        // 跳过当前目录(.)和上级目录(..)        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {            continue;        }        // 使用 stat 函数获取文件信息        <span>struct stat file_stat;</span>        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: %dn", file_count);    return 0;}

登录后复制

文章来自互联网,不代表电脑知识网立场。发布者:,转载请注明出处:https://www.pcxun.com/n/717649.html

(0)
上一篇 2025-06-09 14:35
下一篇 2025-06-09 14:35

相关推荐