linux

Linux readdir如何遍历子目录

小樊
44
2025-04-20 13:35:47
栏目: 智能运维

在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>

0
看了该问题的人还看了