How to construct a file path relative to another path?

61 Views Asked by At

Say my application is running from working directory A and ingests a config file in directory B (for which the absolute path is known). This config file will then reference other files either relative to the config file OR absolute (C). It doesn't have to be part of the same worktree.

For the sake of visualisation:

A (workdir)
├── config
│   └── default.yaml (B) --\
├── data                   | relative (or absolute) path to image (C)
│   └── image.png <--------/
├── tools
│   └── myapp.exe
│ 

How can I now normalize my paths C in relation to the working directory A? Or in other words, how can I make sure paths in C are rewritten in respect to A so that they refer to the same file when looked at by my running application in A? I want to use std::filesystem for that.

2

There are 2 best solutions below

0
Jarod42 On BEST ANSWER

Either resourcePath is absolute or relative, you might use operator/ directly:

const auto final_absolute_path =
    std::filesystem::current_path() / "config" / resourcePath;
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^
//  path where is default.yaml                   path read from that file
8
Alan Birtles On

If your resource path is in resourcePath and your config file's path is configPath then you can just do:

if (resourcePath.is_relative())
{
  resourcePath = configPath.parent_path() / resourcePath;
}