centos

如何使用CentOS readdir遍历子目录

小樊
54
2025-07-20 22:22:40
栏目: 智能运维

在 CentOS 系统中,你可以使用 readdir 函数来遍历子目录

首先,确保你已经安装了必要的开发工具和库。在 CentOS 上,你可以使用以下命令安装:

sudo yum groupinstall "Development Tools"
sudo yum install glibc-devel

接下来,创建一个名为 traverse_directory.c 的 C 文件,并添加以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

void traverse_directory(const char *path) {
    DIR *dir;
    struct dirent *entry;

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

    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_DIR) {
            if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
                continue;
            }
            char path_with_entry[PATH_MAX];
            snprintf(path_with_entry, sizeof(path_with_entry), "%s/%s", path, entry->d_name);
            traverse_directory(path_with_entry);
        } else {
            printf("%s\n", entry->d_name);
        }
    }

    closedir(dir);
}

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

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

保存文件后,使用以下命令编译 C 文件:

gcc -o traverse_directory traverse_directory.c

现在,你可以运行编译后的程序来遍历子目录。例如,要遍历名为 example_directory 的目录,请运行:

./traverse_directory example_directory

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

0
看了该问题的人还看了