centos

CentOS readdir的递归读取方法

小樊
40
2025-05-31 07:10:14
栏目: 智能运维

在 CentOS 系统中,你可以使用 readdir 函数来递归地读取目录。以下是一个使用 C 语言编写的示例程序,展示了如何使用 readdir 函数递归地读取目录及其子目录中的所有文件和文件夹:

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

void read_directory(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 path_buf[PATH_MAX];
        snprintf(path_buf, sizeof(path_buf), "%s/%s", path, entry->d_name);

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

        if (S_ISDIR(statbuf.st_mode)) {
            read_directory(path_buf);
        } else {
            printf("%s\n", path_buf);
        }
    }

    closedir(dir);
}

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

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

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

gcc -o read_directory read_directory.c

现在,你可以使用以下命令运行程序,其中 <directory> 是要递归读取的目录路径:

./read_directory <directory>

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

0
看了该问题的人还看了