I created a program that reads configuration from ini file, the name of that file should be identical to name of executable but of course with its extension. So If I name it myprogram.exe
the config should be myprogram.ini
, and if I change name of the exe after compilation it should look accorting to its new name.
I know that it is possible to get program name from argv[0]
but this works only if it starts from command line, when it is clicked in explorer this array is empty.
As I read through the answers here I think it has to do something with this function: https://stackoverflow.com/a/10572632/393087-但是我找不到该函数用法的任何很好的例子,我是c++的初学者,常规函数定义(如microsoft页面上介绍的函数定义)对我来说太难理解了,但是当我开始工作时举例来说,这对我来说很容易理解。
最佳答案
#include <windows.h>
#include <Shlwapi.h>
// remember to link against shlwapi.lib
// in VC++ this can be done with
#pragma comment(lib, "Shlwapi.lib")
// ...
TCHAR buffer[MAX_PATH]={0};
TCHAR * out;
DWORD bufSize=sizeof(buffer)/sizeof(*buffer);
// Get the fully-qualified path of the executable
if(GetModuleFileName(NULL, buffer, bufSize)==bufSize)
{
// the buffer is too small, handle the error somehow
}
// now buffer = "c:\whatever\yourexecutable.exe"
// Go to the beginning of the file name
out = PathFindFileName(buffer);
// now out = "yourexecutable.exe"
// Set the dot before the extension to 0 (terminate the string there)
*(PathFindExtension(out)) = 0;
// now out = "yourexecutable"
buffer
内部,因此当buffer
超出范围时,out
不再有效。关于c++ - 程序如何获取自身的可执行文件名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10814934/