You answer your own first question, use boost::filesystem::absolute
to get the absolute path from a relative one. You can also look into boost::filesystem::canonical
which removes the symbolic links and special symbols (.
, ..
).
Paths will always be relative to where your executable is being run from i.e. the current working directory, not the path of the executable. There is only one way to fix this consistently: don't use the relative path in your code.
A simple solution is to pass the path to the directory as a command line argument. The following description, previously on SO Docs, makes this easy.
Boost program options provides a simple and safe way to parse and handle command line arguments.
#include <boost/program_options.hpp>
#include <string>
#include <iostream>
int main(int argc, char** argv) {
namespace po = boost::program_options;
po::variables_map vm;
po::options_description desc("Allowed Options");
// declare arguments
desc.add_options()
("name", po::value<std::string>()->required(), "Type your name to be greeted!");
// parse arguments and save them in the variable map (vm)
po::store(po::parse_command_line(argc, argv, desc), vm);
std::cout << "Hello " << vm["name"].as<std::string>() << std::endl;
return 0;
}
Compile and run with:
$ g++ main.cpp -lboost_program_options && ./a.out --name Batman
Hello Batman
You can output a boost::program_options::options_description
object to print the expected argument format:
std::cout << desc << std::endl;
would produce:
Allowed Options:
--name arg Type your name to be greeted!
For a quick hack around in CLion, it's possible to set the working directory of your run via Run -> Edit Configurations
, though I'd highly recommend you go for the more permanent & reliable solution.