0

Suppose I've got following folder structure

/dir/dir2/dir3/program.exe

I want to obtain program.exe file path as it is called. E.g.

// program.exe
#include <iostream>
#include <filesystem>

int main(int argc, char** argv)
{
    std::cout << std::filesytem::current_path() << "\n";
}

But this program.exe works differently if called from different locations:

  • being in dir3
    user@command_line:/dir/dir2/dir3$ ./program.exe
    output: "/dir/dir2/dir3"
  • being in dir2
    user@command_line:/dir/dir2$ ./dir3/program.exe
    output: "/dir/dir2"
  • being in dir
    user@command_line:/dir$ ./dir2/dir3/program.exe
    output: "/dir"

I wish I could obatin exact path of program.exe no matter what location is it called from. Is it possible?
Thank you for your time.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
TenerowiczS
  • 147
  • 6
  • 1
    Perhaps you can get what you need from a combination of `std::filesystem::current_path()` and what is inside `argv[0]`. – Krzysiek Karbowiak May 18 '22 at 14:02
  • 1
    @KrzysiekKarbowiak That doesn't work if the program is found somewhere by using the environment's `PATH` variable. I don't think there's any 100% bullet proof way of getting the full path to the program currently being executed. `boost::filesystem::system_complete` may be one option. – Ted Lyngmo May 18 '22 at 14:04
  • "*I don't think there's any 100% bullet proof way of getting the full path to the program currently being executed*" - No *standard* way, no. But there are certainly *platform-specific* ways. – Remy Lebeau May 18 '22 at 18:25

1 Answers1

0

You are looking for a folder with the working executable. Current path giving your a process current directory

To obtain executable path

For Windows you can use GetModuleFileNameA Win API function:

For examle:

char  exe_name[ MAX_PATH+1 ] = {'\0'};
::GetModuleFileNameA(nullptr,exe_name,MAX_PATH);

For POSIX you can obtain executable path with readlink system call

For example:

char  exe_name[ PATH_MAX+1 ] = {'\0'};
char query[64] = {'\0'};
std::snprintf(query, 64, "/proc/%u/exe", ::getpid() );
::readlink(query, exe_name, PATH_MAX);
Victor Gubin
  • 2,782
  • 10
  • 24
  • Sadly posix solution does not work for me ( it follows the pattern I descirbed in my problem ). Anyway thanks for the trouble. – TenerowiczS May 18 '22 at 14:26