温馨提示×

如何用copendir实现Linux目录树遍历

小樊
45
2025-11-17 12:11:30
栏目: 智能运维

在Linux中,opendir函数用于打开一个目录流,以便后续使用其他相关函数(如readdirclosedir等)来遍历目录内容。以下是一个使用opendirreaddir实现目录树遍历的基本示例:

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

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

        if (S_ISDIR(statbuf.st_mode)) {
            printf("Directory: %s\n", full_path);
            list_directory_contents(full_path); // 递归遍历子目录
        } else {
            printf("File: %s\n", 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;
}

代码说明:

  1. opendir函数:打开指定路径的目录,并返回一个DIR指针。如果打开失败,返回NULL
  2. readdir函数:从目录流中读取下一个目录项,并返回一个struct dirent指针。如果到达目录末尾,返回NULL
  3. closedir函数:关闭目录流。
  4. stat函数:获取文件或目录的状态信息。
  5. 递归遍历:如果遇到子目录,递归调用list_directory_contents函数。

编译和运行:

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

这个程序会递归地遍历指定目录及其所有子目录,并打印出每个文件和目录的完整路径。

0