win32将当前目录切换到程序所在目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int pathGetContainer(const char *path, string &dir)
{
	const char *p;
	for (p = path + strlen(path); p >= path; p--)
	{
		if (*p == '/' || *p == '\\')
			break;
	}
	dir = string(path).substr(0, p - path + 1);
	return 1;
}
 
...
	char curPath[1024];
	GetModuleFileNameA(AfxGetApp()->m_hInstance, curPath, sizeof(curPath));
	string curDir;
	pathGetContainer(curPath, curDir);
	SetCurrentDirectoryA(curDir.c_str());
...