且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 16:01:42

要转换 std :: filesystem :: path 到本地-编码的字符串(其类型为 std :: filesystem :: path :: value_type ),请使用 string() 方法。请注意其他 * string()方法,这些方法使您能够获取特定编码的字符串(例如 u8string()

To convert a std::filesystem::path to a natively-encoded string (whose type is std::filesystem::path::value_type), use the string() method. Note the other *string() methods, which enable you to obtain strings of a specific encoding (e.g. u8string() for an UTF-8 string).

C ++ 17示例:

C++17 example:

#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支持):

C++20 example (better language and library UTF-8 support):

#include <filesystem>
#include <string>

namespace fs = std::filesystem;

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