程序如何获得自己的可执行名称?

时间:2012-05-30 11:00:07

标签: c++ windows

  

可能重复:
  Extracting the current executable name

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

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

当我在这里阅读答案时,我认为它必须对这个函数做一些事情:https://stackoverflow.com/a/10572632/393087 - 但我找不到任何使用该函数的好例子,我是c ++的初学者一般的函数定义(就像在微软页面上看到的那样)对我来说太难理解,但是当我得到一个有效的例子时,我很容易理解。

2 个答案:

答案 0 :(得分:9)

#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无效。

答案 1 :(得分:4)

GetModuleFileName(NULL, .....)

  

但我无法找到使用该功能的任何好例子

You haven't tried hard enough. &#34;实施例&#34;关于msdn的"GetModuleFileName"文章中的部分