0

I've run into a problem on Linux systems that I can't seem to find any concrete solution online for.

I have a C++ application, lets call it Program1. Program1 opens a text file for reading. The text file is in it's parent directory one level up (../test_file.txt). So in code, to open the file:

ifile.open("../test_file.txt");

If you open a terminal in the same directory as Program1 and run the executable:

$ ./Program1 &

Everything works fine. test_file.txt is read without an issue.

Now let's introduce a shell script in a different directory, lets call it ShellScript1. This script execute Program1 and other programs in different directories. The important line the shell script file looks something like this:

../../test/Release/Program1 &

When this shell script is ran Program1 executes but test_file.txt cannot be read. Now as far as I can tell this is because the active directory is the directory of the shell script.

I need to be able to run executables with a shell script that doesn't actively change the relative pathing used in the executable such as with Program1 when ran via shell script.

Is there a way around this? Or is my method of reading in the file in my code need improvement?

Note that I'm running each process as a background process to ensure that I can run each executable simultaneously.

Frank
  • 915
  • 1
  • 7
  • 22
  • The path `../test_file.txt` is relative to current working directory, which may or may not be the same directory where the executable resides. If you want a path relative to executable, compute it. Path to executable is usually passed to `main` in `argv[0]` – Igor Tandetnik Dec 03 '18 at 01:08
  • @eukaryota Thanks for the link. Since that method spawns a "sub-shell" can I assume that the parent script won't have to wait for the exit of that executable to move on to the next executable? I actually tried a similar method like the one you linked but it didn't work when trying to add the `&` character at the end – Frank Dec 03 '18 at 01:15
  • @eukaryota I did consider adding code that checks the current path of the executable and adjusts reading in the file accordingly, but was hoping there was a better, more flexible way. – Frank Dec 03 '18 at 01:17
  • In general, this is not a common way to package applications on Linux. Data files are not usually stored with the executable. – Barmar Dec 03 '18 at 01:18
  • @Barmar I'm assuming the normal Linux method is to store it in some location in the `usr` space or other directory relative to `home`? – Frank Dec 03 '18 at 01:22
  • Yes, or hard-code a default location and use an environment variable to override it. – Barmar Dec 03 '18 at 01:25
  • @Barmar thanks for the clarification. I'll look into it. – Frank Dec 03 '18 at 01:26

0 Answers0