在Windows下C++编程经常需要获得程序路径,因为很多文件都保存在安装文件夹下。
首先百度一下!
1、GetModuleFileName函数定义如下:
DWORD WINAPI GetModuleFileName( _In_opt_ HMODULE hModule, _Out_ LPTSTR lpFilename, _In_ DWORD nSize );
如果想要获取另一个已加载模块的文件路径,可以使用GetModuleFileNameEx函数。
这里的完全路径中包括运行程序的文件名。所以要得到需要文件夹路径需要将文件名去掉……
下面函数的功能实现了,代码如下:
wstring GetProgramDir() { TCHAR exeFullPath[MAX_PATH]; // Full path GetModuleFileName(NULL,exeFullPath,MAX_PATH); wstring strPath = __TEXT(""); strPath = (wstring)exeFullPath; // Get full path of the file int pos = strPath.find_last_of(L'\\', strPath.length()); return strPath.substr(0, pos); // Return the directory without the file name }本来想用 TCHAR和__TEXT这类比较通用的,但是懒了……
调用函数即可得到。
2、GetCurrentDirectory函数
定义如下:
DWORD GetCurrentDirectory( DWORD nBufferLength,//sizeofdirectorybuffer LPTSTR lpBuffer//directorybuffer );
参考文章:
http://www.cnblogs.com/pegasus923/archive/2010/11/02/1867584.html
http://baike.baidu.com/link?url=0zkwvBhzPyZbD4p0qcYuX4yGnKrWcJv01xMm64jHwKKrnhQMuOz4KvTQESCnLOyLbxYMCORp4NMKm7fQRIJEYq
http://baike.baidu.com/link?url=KnnbF7aLBZh7nabBmOgkp2qo7mAXuL5hHi_PVZ5P4pzvsHGG85VQbIgsQYAAAgwbJqTgpeUg4U5A_NQ6CRAjma#2_1