c++c++17

how to convert filesystem path to string


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.

Solution

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