Render paths relative to script location rather than current directory?

I have reproduced the problem in a simple as possible example.
Here is the directory structure:
1
2
3
4
5
6
7
8
9
$ tree
.
├── gen
├── gen.cpp
├── input1.txt
├── version1
│   └── load.sh
└── version2
    └── load.sh


gen.cpp prints an input file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <fstream>
#include <string>
#include <iostream>

#ifdef WINDOWS
 #include <direct.h>
 #define GetCurrentDir _getcwd
#else
 #include <unistd.h>
 #define GetCurrentDir getcwd
#endif

int main(const int argc, const char* const argv[])
{
    std::string path = argv[1];
    std::ifstream stream;    
    stream.open(path);
    std::string line;

    //print input file
    if (!stream.is_open())
    {
        std::cerr << "error: Unable to open input file: " << path << std::endl;
        exit(EXIT_FAILURE);
    }

    std::getline(stream, line, '\n');
    std::cout << "Opened input file: " << path
        << "\nFirst line of input file is: " << line << "\n";
    stream.close();

    //print current directory
    char currentDir[128];

    GetCurrentDir(currentDir, sizeof(currentDir));
    std::cout << "currentDir = " << currentDir << "\n";
}

load.sh passes a relative path "../input1.txt" to gen.cpp:
1
2
#!/bin/bash
../gen "../input1.txt"

The relative paths work as intended when load.sh is called from within the version1 directory:
1
2
3
4
5
6
$ pwd
/home/wolfv/Documents/developer/c++/demo/load_path/version1
$ ./load.sh
Opened input file: ../input1.txt
First line of input file is: hello world
currentDir = /home/wolfv/Documents/developer/c++/demo/load_path/version1

When load.sh is called from outside the directory, the relative path is different, which breaks the paths in load.sh:
1
2
3
4
5
$ cd ..
$ pwd
/home/wolfv/Documents/developer/c++/demo/load_path
$ version1/load.sh
version1/load.sh: line 2: ../gen: No such file or directory

Is there a way to use paths relative to the script location rather than current directory?
I want the paths in load.sh rendered as if they where called from inside the script's directory, no matter were load.sh is called from.

I changed load.sh paths to:
1
2
#!/bin/bash
./gen "input1.txt"

With the new paths, load.sh works as intended when called from directory above version1:
1
2
3
4
5
6
$ pwd
/home/wolfv/Documents/developer/c++/demo/load_path
$ version1/load.sh
Opened input file: input1.txt
First line of input file is: hello world
currentDir = /home/wolfv/Documents/developer/c++/demo/load_path

But then it didn't work when called from within the version1 directory.

Thank you.
Last edited on
Update:

I just discovered the chdir() function. Here is how I plan to use it:
A C++ program changes to the directory containing the load.sh, and then calls the load.sh.

I will post results tomorrow.
Update:

chdir() worked great.
Topic archived. No new replies allowed.