how to convert filesystem path to string

半城伤御伤魂 提交于 2020-02-20 06:46:06

问题


I am iterating through all the files in a folder and just want their names in a string. I want to get a string from a std::filesystem::path. How do I do that?

My code:

#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;
}

However I get the following error:

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

回答1:


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 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 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();
}


来源:https://stackoverflow.com/questions/45401822/how-to-convert-filesystem-path-to-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!