-2

Say I have a directory dirA which contains a c++ program testA and an input file fileA.txt.

testA reads file1.txt by doing something like std::ifstream inFile("./fileA.txt");.

Everythink works fine if I execute the program from within dirA in a shell. However, if I switch do a different directory and run the program, fileA.txt cannot be found.

When I write std::ifstream inFile("./fileA.txt"); in testA, I expected the program runs from any directory, as testA and fileA.txt are in the same directory. However, it does only work if I run testA from dirA.

Is there a way to achieve this?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Simon
  • 325
  • 1
  • 6
  • 3
    Yes, there are ways to "achieve this". One can look at `argv[0]` and determine the executable's actual filename. If it's relative one can then grab `getenv("PATH")` and figure it out from there; and then, in all cases, wind up with the absolute location of the executable, and from there get the full path to the input file. – Sam Varshavchik Aug 24 '23 at 19:13
  • Seems you don't really grasp what the `cwd` (current working directory) of a process is. – Jesper Juhl Aug 24 '23 at 21:52
  • @SamVarshavchik `argv[0]` returns just the string to the command line when I run the program, i.e., `./testA`in my case. `getenv("PATH")` also contains only standard paths such as `/usr/local/bin` . So how would you combine these information to wind up the absolute location of the executable ? – Simon Aug 25 '23 at 07:33
  • If `argv[0]` is `./testA`, then the executable must be in `.`, and you use that. For a path relative to the current directory combine it with `getcwd()` or `std::filesystem::current_path` in order to get the absolute path. – Sam Varshavchik Aug 25 '23 at 12:19

0 Answers0