c++

c++ opendir函数如何处理符号链接

小樊
81
2024-09-13 04:10:33
栏目: 编程语言

opendir() 函数是用于打开一个目录流,它允许你逐个读取目录中的文件和子目录

以下是一个简单的示例,展示了如何使用 opendir()readdir() 函数处理符号链接:

#include<iostream>
#include<string>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    DIR *dir;
    struct dirent *entry;
    struct stat statbuf;

    // 打开目录
    dir = opendir(".");
    if (dir == NULL) {
        std::cerr << "Error opening directory"<< std::endl;
        return 1;
    }

    // 逐个读取目录项
    while ((entry = readdir(dir)) != NULL) {
        // 获取目录项的完整路径
        std::string full_path = "./" + std::string(entry->d_name);

        // 获取目录项的状态信息
        if (lstat(full_path.c_str(), &statbuf) == -1) {
            std::cerr << "Error getting file status: "<< entry->d_name<< std::endl;
            continue;
        }

        // 判断是否为符号链接
        if (S_ISLNK(statbuf.st_mode)) {
            std::cout << "Symbolic link: "<< entry->d_name<< std::endl;
        } else {
            std::cout << "Regular file or directory: "<< entry->d_name<< std::endl;
        }
    }

    // 关闭目录流
    closedir(dir);

    return 0;
}

在这个示例中,我们首先使用 opendir() 函数打开当前目录(.)。然后,我们使用 readdir() 函数逐个读取目录项。对于每个目录项,我们使用 lstat() 函数获取其状态信息,并检查它是否是一个符号链接。如果是符号链接,我们输出相应的信息;否则,我们输出它是一个普通文件或目录。最后,我们使用 closedir() 函数关闭目录流。

0
看了该问题的人还看了