How to convert boost path type to string?

C++BoostPath

C++ Problem Overview


Hello I currently have a program that gets a full path of a file's location and is put into a variable that is the type of: boost::filesystem2::path

I have looked up how to do this and have found that using:

string result1 = boost::filesystem::basename (myPath)

will convert the path to string BUT it only converts the file name (e.g. if the path is "C:\name\bobsAwesomeWordDoc.docx" it just returns "bobsAwesomeWordDoc").

I have found the following on how to convert the entire path to string, but I don't know how to implement it in my program. I have tried multiple ways but I am getting conversion errors.

>const std::string& string( ): This routine returns a copy of the string with which the path was initialized, with formatting per the path grammar rules.

(found here)

I have tried:

string result1 = string& (myPath);

and a few other variations.

C++ Solutions


Solution 1 - C++

You just need to call myPath.string().

Solution 2 - C++

I believe you need to do a little more than just convert the path to a string - you should first obtain the canonical version of the path - an absolute path with no symbolic-link elements - and convert that into a string:

boost::filesystem::canonical(myPath).string();

P.S. - I've been programming with Boost for ages and I couldn't easily find this info in the docs.


Update (Oct 2017)

Documentation: boost::filesystem::canonical.

But note that as of C++17 there is std::filesystem, with canonical and a lot more.

Solution 3 - C++

This worked in wxWidgets: (I know I should just use the wx utilities but it is a test)

void WxWidgetsBoostTestFrame::OnTestBtnClick(wxCommandEvent& event)
{
    boost::filesystem::path currentPath;
    currentPath = boost::filesystem::current_path();
    std::string curDirString;
    curDirString = boost::filesystem::canonical(currentPath).string();
    wxString mystring(curDirString.c_str(), wxConvUTF8);
    wxMessageBox(mystring); // output:  C:/Users\client\Desktop...      
}

Solution 4 - C++

Calling myPath.generic_string() will do what you need.

Solution 5 - C++

Personally I had to do

boost::filesystem::absolute(path).string()

to get it to work, as:

path.string()

kept returning a relative path.

Solution 6 - C++

Do this

    path.c_str();

You should be fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnstonView Question on Stackoverflow
Solution 1 - C++icecrimeView Answer on Stackoverflow
Solution 2 - C++resignedView Answer on Stackoverflow
Solution 3 - C++PaddyView Answer on Stackoverflow
Solution 4 - C++J.AdlerView Answer on Stackoverflow
Solution 5 - C++BrianView Answer on Stackoverflow
Solution 6 - C++CalorifiedView Answer on Stackoverflow