商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > readdir如何实现跨平台文件操作

readdir如何实现跨平台文件操作

  发布于2026-07-06 阅读(0)

扫一扫,手机访问

readdir 这个函数,熟悉 POSIX 标准的朋友应该不陌生,它在 Linux 和 macOS 这类 Unix-like 系统上非常常用,主要负责读取目录内容。但问题来了:如果要把同样的功能搬到 Windows 上,直接套用 readdir 肯定行不通。那怎么办?其实,C++17 引入的 库就是跨平台的首选,实在不行,Boost.Filesystem 也是稳妥的后备方案。

readdir如何实现跨平台文件操作

先看 C++17 的写法。用 std::filesystem 处理目录遍历,代码简洁得让人舒服:

#include 
#include 

namespace fs = std::filesystem;

int main() {
    std::string path = "your_directory_path_here";
    if (fs::exists(path) && fs::is_directory(path)) {
        for (const auto& entry : fs::directory_iterator(path)) {
            std::cout << entry.path() << std::endl;
        }
    } else {
        std::cerr << "The specified path does not exist or is not a directory." << std::endl;
    }
    return 0;
}

如果你还在用较旧的 C++ 标准,或者项目中已经集成了 Boost,那 Boost.Filesystem 的方案同样可靠:

#include 
#include 

namespace fs = boost::filesystem;

int main() {
    std::string path = "your_directory_path_here";
    if (fs::exists(path) && fs::is_directory(path)) {
        for (fs::directory_iterator it(path); it != fs::directory_iterator(); ++it) {
            std::cout << it->path() << std::endl;
        }
    } else {
        std::cerr << "The specified path does not exist or is not a directory." << std::endl;
    }
    return 0;
}

两个示例的核心逻辑完全一致:先判断路径是否存在、是否为目录,然后遍历该目录下的所有文件和子目录,把它们的路径打印到控制台。唯一需要你动手替换的是代码中的 your_directory_path_here,换成你实际要读取的目录路径就行。就这么简单。

本文转载于:https://www.yisu.com/ask/43374731.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注