0

I have a program written in C. It's directory structure is like this:

root/
    program.sh
    textures/
        texture1.png

program.sh imports textures in a way like: load_textures("./textures/texture1.png") (relative paths). Hence, the program only works whenever I execute program.sh from the root directory.

I want to create a link to program.sh such that, whenever I execute the link, I am able to execute the program.sh from the root directory. In other words, I want to execute program.sh from outside the root directory.

Now, I would prefer a solution to do this without changing the source code (if there is a way), otherwise, how would you recommend that I open files/textures in C, given the current scenario?

Had a similar question here, but it's unanswered.

MaJoR
  • 954
  • 7
  • 20
  • 1
    Are you just looking to change the current working directory of the program when executed from the link? – aaaaaa123456789 Mar 10 '19 at 07:17
  • The program is using a relative path to the assets. So, if I change the directory, it will work. But I want to come back to the directory from where I was before, after the execution. – MaJoR Mar 10 '19 at 07:20
  • You can do that with a simple shell script: `pushd` into your desired directory, execute the program from there, and `popd`. – aaaaaa123456789 Mar 10 '19 at 07:21
  • So, I make a wrapper-ish script, using `pushd` and `popd` to execute the program? – MaJoR Mar 10 '19 at 07:22
  • 1
    Yep. You can even pass the command-line arguments given to the script into your program. I mean, you _can_ do this from a separate C program, but it's not worth it. – aaaaaa123456789 Mar 10 '19 at 07:25
  • 1
    Just a bit of googling about `pushd` and `popd`, and I found [this](https://stackoverflow.com/a/31391814/8726146). Thanks a lot, fellow Sir. :D – MaJoR Mar 10 '19 at 07:27
  • Would you post an answer, so that I can mark it as solved, and you get that sweet karma? Or, do I just flag the question as a duplicate (:P). – MaJoR Mar 10 '19 at 07:28
  • 1
    Sure, I'll make a post. – aaaaaa123456789 Mar 10 '19 at 07:30

1 Answers1

1

As it became clear from comments, the goal was to execute the program from a different directory, but with the program's current working directory pointing to its own directory.

While this can be done in C (in a POSIX system, as assumed due to the .sh extension, via a combination of the chdir and execvp syscalls), it's much more easily achieved in a wrapper shell script, like so:

#!/bin/sh

pushd /path/to/executable
./program.sh $@
popd
aaaaaa123456789
  • 5,541
  • 1
  • 20
  • 33