Search code examples
c++boost-filesystem

c++ - BOOST filesystem path from variable string


I ran into this issue when creating a boost::filesystem::path object (boost v1.55). I couldn't figure out how to create a path from from a String variable, or concatenation of Strings?

//Example 1
namespace fs = boost::filesystem;
String dest = "C:/Users/username";  
fs::path destination (dest); //Error here

//Example 2
namespace fs = boost::filesystem;
String user = "username";
fs::path destination ("C:/Users/" + user); //Error here as well.

//Example 3
namespace fs = boost::filesystem;
fs::path destination ("C:/Users/username");

I've only been able to create a path object when the entire string is specified between double quotes like example 3 above, but this does not allow for a variable input.

Basically, how would I implement the fs::path object class using a String as my starting point?

Thanks for any assistance!

edit

Link to boost/filesystem path documentation. Relearning c++, so a some of it is still a bit over my head... I don't quite understand how the constructor works here... and really don't know what to ask at this point.... I'd definitely appreciate any pointers.


Solution

  • Thanks GManNickG - you actually managed to solve my issue. I'm using C++ builder 10.1, and was able to mess with String for a while, assigning it values, etc. It was actually the ShowMessage() method that led me to my answer - in c++ builder, it wants an AnsiString argument to work, and a std::string wouldn't compile. C++ Builder 10.1 defines String to be an AnsiString, not std::string. Again, I'm newish to c++ so when using namespace std I didn't realize the difference (most of my prior knowledge of Obj Oriented is from java where you define a string as String.

    //Working Example in C++ Builder 10.1 Starter
    namespace fs = boost::filesystem;
    std::string un = "/username";
    std::string dest = "C:/Users" + un;  //concatenation test
    fs::path destination (dest); //Works, no compiler error now
    
    std::string pathStdString = destination.string(); //retrieve 'dest' as std:string from path
    String pathAnsiString = pathStdString.c_str(); //Converts std::string to ansi
    
    ShowMessage(pathAnsiString); //Output box showing the path (valid in C++ Builder)
    

    Hopefully this helps someone else coming along with a similar issue. Also, link to how std::converts to Ansi in case anyone finds it useful.