c++ - 如何从文件系统获取 std::string 或 char[]?

标签 c++

我有一个遍历整个目录的循环,我需要从每个文件获取路径才能使用它。

这是我的方法

#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

for (const auto & entry : fs::directory_iterator(sourceDir))
{
    if (fs::is_directory(entry))
        continue;
    StreamRAII iStream{ entry, StreamMode::READ_BINARY };
}

问题是 StreamRAII 构造函数必须将 std::string 作为其第一个参数

StreamRAII(const std::string& filename, const char *mode);

但是这个 const auto & entry : fs::directory_iterator(sourceDir), entryderectory_entry 类型。

问题是,如何获取我的文件的路径?如何将 derectory_entry 转换为 std::stringchar[]

P.S. 当我使用 cout 时,我可以看到我的文件的路径...

最佳答案

derectory_entry有一个path()返回 std::filesystem::path 的函数保存文件的路径名。您可以使用它的 string()从该路径获取 std::string 的函数。这将使您的代码看起来像

StreamRAII iStream{ entry.path().string(), StreamMode::READ_BINARY };

关于c++ - 如何从文件系统获取 std::string 或 char[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57376463/

相关文章:

c++ - 从作用于 map 的算法调用的仿函数可以接受 pair<K, V> 而不是 value_type 吗?

C++ std::bad_alloc 错误

c++ - 使用 strcmp() 比较两个 C 字符串数组

c++ - 预排序基于数组的二叉搜索树

c++ - 将 CMake 项目导入 CodeLIte

c++ - 如何防止使用 ofstream 覆盖文本文件中的信息?

c++ - 满足条件时如何取消 std::async?

c++ - 无法成功创建唯一对象的 std::list

c++ - vector访问速度,哪种方法更快?

c++ - 通过命令行中的ffmpeg或opencv从IP摄像头捕获图像获取灰度图像