35

How can I use boost::filesystem::path to specify a relative path on Windows? This attempt fails:

boost:filesystem::path full_path("../asset/toolbox"); // invalid path or directory.

Maybe to help me debug, how to get the current working directory with boost::filesystem?

1
  • Just to clarify, I solved my problem. The above method is correct for relative path access. However, in MSVS the current working directory was not what I had expected. hmuelner's currentpath() helped. Commented Oct 16, 2010 at 15:03

4 Answers 4

75
getcwd = boost::filesystem::path full_path(boost::filesystem::current_path());

Example:

boost::filesystem::path full_path(boost::filesystem::current_path());
std::cout << "Current path is : " << full_path << std::endl;

To access current_path one needs to add #include <boost/filesystem.hpp>.

Sign up to request clarification or add additional context in comments.

2 Comments

there seems to be a flaw here, this is not a valid C++ expression, is there missing something in between boost::filesystem::path and full_path?
This is not a valid C++ expression, but a short-cut notation for the answer. In modern C++ you could write: auto cwd = boost::filesystem::current_path();
21

Try the system_complete function.

namespace fs = boost::filesystem;

fs::path full_path = fs::system_complete("../asset/toolbox");

This mimics exactly how the OS itself would resolve relative paths.

Comments

2

If you want to change to previous directory then try something like this:

boost::filesystem::path full_path( boost::filesystem::current_path() );
std::cout << "Current path is : " << full_path << std::endl;

//system("cd ../"); // change to previous dir -- this is NOT working
chdir("../"); // change to previous dir -- this IS working

boost::filesystem::path new_full_path( boost::filesystem::current_path() );
std::cout << "Current path is : " << new_full_path << std::endl;

Comments

0

When you type "../your/path" aren't you specifying a unix-like path? I think what you should do to get system specific paths is:

boost:filesystem::path full_path(".." / "asset" / "toolbox");

In this case the '/' is an operator concatenating paths in a system specific way and is not part of the path that you specify.

3 Comments

Not really... You're specifying a path in the internal boost::filesystem format, which is somewhat unix-like. I also like the operator notation better though. You'd have to do something like path full_path = path("..") / "asset" / "toolbox";
And in windows you can use / as directory delimiter as well.
must be boost:filesystem::path full_path(boost:filesystem::path(".." )/ "asset" / "toolbox");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.