Search code examples
c++execution

Indirect Path to Files, when program is called from somewhere else


I have a problem with my C++ console program. I need some dictionary files for some translations. So I read this Files in the program and gave them a indirect path to the program folder.

String="translation\\PfadzuDatei\\Datei.txt";

In Debugging-Mode this works great, because VS starts the program in the right directory, but when i release it, and it is called from somewhere else like:

Path of Program: c:\Program.exe

And i start it from: another position:

C:\anyPathInConsole\>c:\Program.exe arg1

The program is not able to find the translation files.

Is there any other possibility to set the Path to the files in other ways or do i have to call the program from C:\

The problem with calling the program from the specific folder is, that the program is started by a nodejs "Child-Prozess" exec function and i don`t know the executing Path.


Solution

  • I do not know what operating system the author uses, I will assume that windows. You can get the absolute path to the file by concatenating path to *.exe and relative file path:

    std::string getPath()
    {
       char buf[256];
       // Get file name
       GetModuleFileNameA(nullptr, &buf[0], sizeof(buf));
    
       // Extract path from full name
       std::string path = buf;
       const size_t last_slash_idx = path.rfind('\\');
       if (std::string::npos != last_slash_idx)
       {
          path = path.substr(0, last_slash_idx);
       }
       // Add relative path
       path += "\\";
       path += "translation\\PfadzuDatei\\Datei.txt";
       return path;
    }
    

    For lixux readlink("/proc/self/exe", buf, sizeof(buf)); can be used instead GetModuleFileNameA