ubuntu

ubuntu readdir 如何实现递归读取

小樊
37
2025-12-27 17:57:39
栏目: 智能运维

在 Ubuntu 中,要实现递归读取目录(包括子目录)的内容,可以使用多种方法。以下介绍几种常用的方法,包括使用命令行工具和编写 C 程序。

方法一:使用 find 命令

find 是一个强大的命令行工具,用于在目录树中搜索文件和目录。

基本用法

find /path/to/directory -type f

示例

假设要递归列出 /home/user/Documents 目录下的所有 .txt 文件:

find /home/user/Documents -type f -name "*.txt"

其他选项

方法二:使用 tree 命令

tree 命令以树状结构显示目录内容,支持递归显示子目录。

安装 tree

如果尚未安装,可以使用以下命令安装:

sudo apt update
sudo apt install tree

使用方法

tree /path/to/directory

方法三:使用 lsgrep 组合

虽然不如 find 强大,但简单的组合也可以实现基本的递归读取。

示例

列出所有 .txt 文件:

ls -R /path/to/directory | grep "\.txt$"

注意事项

方法四:编写 C 程序递归读取目录

如果需要在程序中实现递归读取目录,可以使用 C 语言的 dirent.h 库。

示例代码

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

void list_directory_recursive(const char *path) {
    DIR *dir = opendir(path);
    if (dir == NULL) {
        perror("opendir");
        return;
    }

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

        char fullpath[1024];
        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);

        struct stat st;
        if (stat(fullpath, &st) == -1) {
            perror("stat");
            continue;
        }

        if (S_ISDIR(st.st_mode)) {
            printf("Directory: %s\n", fullpath);
            list_directory_recursive(fullpath);
        } else {
            printf("File: %s\n", fullpath);
        }
    }

    closedir(dir);
}

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

    list_directory_recursive(argv[1]);
    return EXIT_SUCCESS;
}

编译与运行

保存上述代码为 listdir.c,然后使用以下命令编译和运行:

gcc -o listdir listdir.c
./listdir /path/to/directory

说明

方法五:使用 Python 脚本

对于喜欢脚本编程的用户,Python 提供了简洁的方法来递归读取目录。

示例代码

import os

def list_directory_recursive(path):
    for root, dirs, files in os.walk(path):
        for name in files:
            print(os.path.join(root, name))
        # 如果需要处理目录,可以在这里添加代码

if __name__ == "__main__":
    target_directory = "/path/to/directory"
    list_directory_recursive(target_directory)

运行方法

将上述代码保存为 listdir.py,然后在终端中运行:

python3 listdir.py

说明

总结

在 Ubuntu 中,递归读取目录内容有多种实现方式,选择具体方法取决于实际需求和使用场景:

希望以上方法能帮助您在 Ubuntu 系统中实现递归读取目录的需求!

0
看了该问题的人还看了