在程序中获得可执行文件的路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u79501/article/details/72820438

有时候我们需要在程序中获得可执行程序的路径,可以采用下面这个函数:

std::wstring GetExePath(bool bwithexe)
{
	std::wstring sFullPath;//全路径,例如:"D:\program files\a.exe"
	std::wstring sBarePath;//不含程序名路径,例如: "D:\program files"

	TCHAR chpath[MAX_PATH];
	GetModuleFileNameW(NULL, (LPWSTR)chpath, sizeof(chpath));
	sFullPath = chpath;
	std::wstring::size_type nPos = sFullPath.find_last_of(L"\\");
	if (nPos != std::wstring::npos)
	{
		sBarePath = sFullPath.substr(0, nPos);
	}

	return (bwithexe ? sFullPath : sBarePath);
}

一般使用的时候,都是想获得exe目录下的某个文件的路径,可以这么用:

std::wstring file = GetExePath(false) + std::wstring(L"\\xxx.xx");//注意,双反斜杠

然后,调用file.c_str()即可。

说明:

这里使用宽字节wstring,如果要打印出来的话,可以使用这个函数:

wprintf(L"%ls", file.c_str());
但是,打印出来的话,看到的用'\'分隔的。


猜你喜欢

转载自blog.csdn.net/u79501/article/details/72820438