c++ - 如何将文件系统路径转换为字符串

标签 c++ c++17

我正在遍历一个文件夹中的所有文件,只希望它们的名称在一个字符串中。我想从 std::filesystem::path 中获取一个字符串。我该怎么做?

我的代码:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::experimental::filesystem;

int main()
{
    std::string path = "C:/Users/user1/Desktop";
    for (auto & p : fs::directory_iterator(path))
        std::string fileName = p.path;
}

但是我得到以下错误:

non-standard syntax; use '&' to create a pointer to a member.

最佳答案

转换 std::filesystem::path到 native 编码的字符串(其类型为 std::filesystem::path::value_type),使用 string()方法。请注意其他 *string() 方法,它们使您能够获取特定编码的字符串(例如,u8string() 用于 UTF-8 字符串)。

C++17 示例:

#include <filesystem>
#include <string>

namespace fs = std::filesystem;

int main()
{
    fs::path path{fs::u8path(u8"愛.txt")};
    std::string path_string{path.u8string()};
}

C++20 示例(更好的语言和库 UTF-8 支持):

#include <filesystem>
#include <string>

namespace fs = std::filesystem;

int main()
{
    fs::path path{u8"愛.txt"};
    std::u8string path_string{path.u8string()};
}

关于c++ - 如何将文件系统路径转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401822/

相关文章:

c++ - 通过 CRTP 使用派生类变量初始化基类静态常量变量

c++ - 我只是无法理解 DR 712

c++ - VS 2015 C++ Redistributable 不在单个 DLL 中?

c++ - 如何使用 lambda 来进行 std::invoke 惰性求值?

c++ - 确保 char 指针始终指向相同的字符串文字

c++ - 为什么 SFINAE 在这种情况下不起作用?

c++ - 如何为类特定的 typedef (c++17) 启用自动类型推导?

c++ - C++ 中的动态数据类型转换

c++ - Unix Domain Sockets, Udp Sockets Objective C 有什么用?

c++解析文件并读取二进制文件