linux

使用copendir实现Linux目录递归遍历

小樊
43
2025-09-17 10:17:40
栏目: 智能运维

在Linux中,可以使用opendir()readdir()closedir()函数来实现目录的递归遍历。下面是一个简单的示例代码,展示了如何使用这些函数来递归遍历一个目录及其子目录中的所有文件和文件夹:

#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) {
        // Skip current and parent directory entries
        if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
            continue;
        }

        // Construct full path
        char full_path[PATH_MAX];
        snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);

        // Get file/directory information
        if (stat(full_path, &path_stat) == -1) {
            perror("stat");
            continue;
        }

        // Print the name of the file/directory
        printf("%s\n", full_path);

        // If it's a directory, recurse into it
        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>\n", argv[0]);
        return EXIT_FAILURE;
    }

    list_directory_contents(argv[1]);

    return EXIT_SUCCESS;
}

这个程序接受一个命令行参数,即要遍历的目录路径。它会打开目录,读取其中的条目,并打印出每个文件和子目录的完整路径。如果遇到子目录,它会递归地调用list_directory_contents()函数来遍历子目录中的内容。

要编译这个程序,你可以使用gcc

gcc -o listdir listdir.c

然后运行它,传入你想要遍历的目录路径:

./listdir /path/to/directory

请注意,这个程序没有处理符号链接,如果目录中包含符号链接,可能会导致无限递归。此外,错误处理也比较简单,实际使用时可能需要更详细的错误检查和处理。

0
看了该问题的人还看了