Search code examples
c++c++17

Convert a string to std filesystem path


A file path is passed as a string. How do I convert this string to a std::filesystem::path? Example:

#include <filesystem>

std::string inputPath = "a/custom/path.ext";
const std::filesystem::path path = inputPath; // Is this assignment safe?

Solution

  • Yes, this construction is safe:

    const std::filesystem::path path = inputPath; // Is this assignment safe?
    

    That is not assignment, that is copy initialization. You are invoking this constructor:

    template< class Source >
    path( const Source& source );
    

    which takes:

    Constructs the path from a character sequence provided by source (4), which is a pointer or an input iterator to a null-terminated character/wide character sequence, an std::basic_string or an std::basic_string_view,

    So you're fine. Plus, it would be really weird if you couldn't construct a filesystem::path from a std::string.


    See this answer for issues with Windows encodings.