Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert filesystem path to string

Tags:

c++

c++17

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. 
like image 516
anonymous noob Avatar asked Jul 30 '17 16:07

anonymous noob


1 Answers

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()}; } 
like image 136
tambre Avatar answered Sep 20 '22 20:09

tambre