Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...