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

how to convert filesystem path to string

本文关键字:转换 字符串 路径 文件系统      更新时间:2023-10-16

我正在遍历文件夹中的所有文件,只希望它们的名称在一个字符串中。我想从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转换为本机编码的字符串(类型为std::filesystem::path::value_type(,请使用string()方法。请注意其他*string()方法,它们使您能够获得特定编码的字符串(例如 对于 UTF-8 字符串u8string()(。

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++ 17 及更高版本中,您可以使用 .generic_string(( 将路径转换为字符串:https://en.cppreference.com/w/cpp/filesystem/path/generic_string。

下面是获取当前工作目录并将其转换为字符串的示例。

#include <string>
#include <filesystem>
using std::filesystem::current_path;
int main()
{
filesystem::path directoryPath = current_path();
string stringpath = directoryPath.generic_string();
}

使用 UTF-8 操作的公认答案中给出的示例很好,是一个很好的指南。答案中给出的介绍性解释中只有一个错误,Windows/MSVC 开发人员应该注意:

string()方法返回本机编码的字符串(在 Windows 上会std::wstring()(,而是始终返回std::string。它还尝试将路径转换为本地编码,如果路径包含当前代码页中不可表示的 unicode 字符,然后该方法引发异常,则并不总是可行的!

如果你真的想要答案中描述的行为(方法返回本机字符串,即在 Linux 上std::string,在 Windows 上std::wstring(,你必须使用native()方法或基于std::filesystem::path::operator string_type()的隐式转换,但正如@tambre示例中正确指出的那样,您应该考虑始终使用 UTF-8 版本。