debian

如何在Debian中使用readdir进行递归遍历

小樊
37
2025-05-09 21:31:32
栏目: 智能运维

在Debian中,你可以使用C语言编写一个程序来实现递归遍历目录(使用readdir函数)

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

void list_directory_contents(const char *path);

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

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

void list_directory_contents(const char *path) {
    DIR *dir;
    struct dirent *entry;
    struct stat path_stat;
    char full_path[PATH_MAX];

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

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

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

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

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

    closedir(dir);
}

将此代码保存为recursive_readdir.c,然后使用以下命令编译:

gcc -o recursive_readdir recursive_readdir.c

现在,你可以运行这个程序来递归遍历目录:

./recursive_readdir /path/to/directory

这将输出指定目录及其所有子目录中的文件和文件夹。

0
看了该问题的人还看了