#include "stdafx.h"
#include <iostream>
#include <shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
using namespace std;
const char* GetAppPath()
{
static char* pStrPath = NULL;
if (pStrPath == NULL)
{
pStrPath = new char[256];
memset(pStrPath, 0, 256);
GetModuleFileName(NULL, pStrPath, 256);
PathRemoveFileSpec(pStrPath);
}
return pStrPath;
}
int _tmain(int argc, _TCHAR* argv[])
{
const char* pPath = GetAppPath();
cout << pPath << endl;
system("pause");
return 0;
}</span>
需要注意的是,如果没有#pragma comment(lib, "shlwapi.lib"),代码是编译不过的。
还有一个类似的函数GetCurrentDirectory返回当前进程的当前目录,并不一定返回你的应用程序的目录。如果你在应用程序中调用了打开文件对话框,你选择了一个文件,那么,这个文件所在的目录就成了当前进程的当前目录了。
本文介绍了一种使用C++获取当前运行程序路径的方法,通过调用GetModuleFileName和PathRemoveFileSpec函数来实现。此外,还对比了GetCurrentDirectory函数的区别,并强调了在特定情况下后者可能返回的不是程序路径。
9564

被折叠的 条评论
为什么被折叠?



