1

I'm writig ML engine and have tests for testing different models. Project structure looks like that:

- src
-- model1.cpp
- test
-- models
--- model1.bin
-- src
--- model1Test.cpp 

so in my test file I know relative path, which is ../models/model1.bin

My first question is: how could I convert it to absolute one?

And second. I use Clion ide and when you building project, it's actually build it in other place, not the same where sources located (for example /home/uuser1/.clion/cache/bla/bla/debug/). And it's not copy model to that folder. So when I using boost::filesystem::absolute(relative) it's return me the path from executing point, not from the source one. How to deal with it?

silent_coder
  • 6,222
  • 14
  • 47
  • 91

1 Answers1

3

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
paul-g
  • 3,797
  • 2
  • 21
  • 36