程序如何获取自身的可执行名称

How can program get executable name of itself?

本文关键字:可执行 何获取 获取 程序      更新时间:2023-10-16

可能的重复项:
提取当前可执行文件名称

我创建了一个从 ini 文件读取配置的程序,该文件的名称应该与可执行文件的名称相同,但当然还有它的扩展名。因此,如果我将其命名myprogram.exe则配置应该是myprogram.ini的,如果我在编译后更改exe的名称,它应该看起来与它的新名称一致。

我知道可以从argv[0]获取程序名称,但这只有在从命令行启动时才有效,当它在资源管理器中单击时,此数组为空。

当我阅读这里的答案时,我认为它必须与这个函数有关: 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:whateveryourexecutable.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不再有效。

GetModuleFileName(NULL, .....)

但是我找不到使用该函数的任何好例子

你还不够努力。msdn 上的"获取模块文件名"文章中的"示例"部分