从其他地方调用程序时文件的间接路径 [英] Indirect Path to Files, when program is called from somewhere else
问题描述
我的C ++控制台程序有问题.我需要一些词典文件来进行某些翻译.因此,我在程序中读取了这些文件,并给了它们一个指向程序文件夹的间接路径.
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";
在Debugging-Mode(调试模式)下,它非常有用,因为VS在正确的目录中启动程序,但是当我释放它时,它会从其他地方调用,例如:
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
我从另一个位置开始:
C:\anyPathInConsole\>c:\Program.exe arg1
程序无法找到翻译文件.
The program is not able to find the translation files.
是否还有其他可能性以其他方式设置文件的路径,还是我必须从C:\
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:\
从特定文件夹调用程序的问题是,该程序是由nodejs"Child-Prozess"执行函数启动的,而我不知道正在执行的路径.
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.
推荐答案
我不知道作者使用的是哪种操作系统,我假设使用Windows.您可以通过将* .exe的路径和相对文件路径串联起来来获取文件的绝对路径:
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;
}
对于lixux,可以使用readlink("/proc/self/exe", buf, sizeof(buf));
代替GetModuleFileNameA
For lixux readlink("/proc/self/exe", buf, sizeof(buf));
can be used instead GetModuleFileNameA
这篇关于从其他地方调用程序时文件的间接路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!