#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"
现在,您有一个指向可执行文件“基本名称”的指针;请记住,它指向 inside buffer
,因此buffer
超出范围时out
不再有效。