Linux readdir如何遍历子目录

在Linux中,使用readdir函数可以遍历目录及其子目录。以下是一个简单的示例,展示了如何使用readdir函数遍历目录及其子目录:#include #include #include #include #include void list_directory_contents(co

Linux中,使用readdir函数可以遍历目录及其子目录。以下是一个简单的示例,展示了如何使用readdir函数遍历目录及其子目录:

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

    if (!(dir = opendir(path))) {
        perror("opendir");
        return;
    }

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

        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        if (lstat(full_path, &statbuf) == -1) {
            perror("lstat");
            continue;
        }

        if (S_ISDIR(statbuf.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path);
        } else {
            printf("File: %s\n", full_path);
        }
    }

    closedir(dir);
}

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

    list_directory_contents(argv[1]);
    return EXIT_SUCCESS;
}

这个程序接受一个目录作为命令行参数,然后使用readdir函数遍历该目录及其子目录。对于每个条目,它首先检查是否是...,然后使用lstat函数获取文件的状态信息。如果状态信息表示这是一个目录,程序会递归调用list_directory_contents函数来遍历子目录。否则,它会打印文件名。

要编译此程序,请将其保存为list_directory_contents.c,然后在终端中运行以下命令:

gcc -o list_directory_contents list_directory_contents.c

现在,您可以使用以下命令运行程序,其中<directory>是要遍历的目录:

./list_directory_contents <directory>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1301206.html

(0)
派派
上一篇 2025-04-20
下一篇 2025-04-20

发表回复

登录后才能评论