首页主机资讯如何用copendir实现Linux目录树遍历

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

时间2025-11-17 21:43:04发布访客分类主机资讯浏览1479
导读:在Linux中,opendir函数用于打开一个目录流,以便后续使用其他相关函数(如readdir、closedir等)来遍历目录内容。以下是一个使用opendir和readdir实现目录树遍历的基本示例: #include <stdi...

在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

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

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 如何用copendir实现Linux目录树遍历
本文地址: https://pptw.com/jishu/749375.html
Golang在Debian上性能如何调 Linux中copendir的内存管理如何进行

游客 回复需填写必要信息