我正在遍历一个文件夹中的所有文件,只希望它们的名称在一个字符串中。我想从 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/