linux

Linux中如何使用readdir与copendir配合

小樊
43
2025-09-11 10:36:24
栏目: 智能运维

在Linux中,readdircopendir是用于遍历目录内容的两个函数。它们通常与dirent.h头文件一起使用。下面是一个简单的示例,展示了如何使用这两个函数来遍历一个目录及其子目录中的所有文件和文件夹。

#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 path_stat;

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

    while ((entry = readdir(dir)) != NULL) {
        // 跳过当前目录(.)和上级目录(..)
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // 拼接完整路径
        char full_path[1024];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        // 获取文件/目录信息
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // 打印文件/目录名
        printf("%s\n", full_path);

        // 如果是目录,则递归遍历
        if (S_ISDIR(path_stat.st_mode)) {
            list_directory_contents(full_path);
        }
    }

    closedir(dir);
}

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

    list_directory_contents(argv[1]);

    return 0;
}

这个程序接受一个目录路径作为命令行参数,然后使用opendir打开该目录。接着,它使用readdir函数读取目录中的每个条目。对于每个条目,它使用stat函数获取文件或目录的信息,并打印其名称。如果遇到子目录,程序会递归地调用list_directory_contents函数来遍历子目录。

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

gcc -o list_dir list_dir.c

现在,您可以使用以下命令运行程序,列出指定目录及其子目录中的所有文件和文件夹:

./list_dir /path/to/directory

0
看了该问题的人还看了