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

半腔热情 提交于 2019-12-13 08:02:35

问题


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.


回答1:


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




回答2:


I found out the path where the "Child-Process" from my nodejs-Server executes the program. It's the Project-Folder, not the folder of my js-File. Thank you for your Input. I copied the files to my project folder. Sorry for wasting of your time.



来源:https://stackoverflow.com/questions/53724459/indirect-path-to-files-when-program-is-called-from-somewhere-else

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!