Windows環境下的C++獲取當前程式的exe檔案路徑
1. #include "stdafx.h"
2. #include <Windows.h>
3. #include <iostream>
4. #include <string>
5. using namespace std;
6.
7. string GetProgramDir()
8. {
9. wchar_t exeFullPath[MAX_PATH]; // Full path
10. string strPath = "";
11.
12. GetModuleFileName(NULL,exeFullPath,MAX_PATH);
13. char CharString[MAX_PATH];
14. size_t convertedChars = 0;
15. wcstombs_s(&convertedChars, CharString, MAX_PATH, exeFullPath , _TRUNCATE);
16.
17. strPath=(string)CharString; // Get full path of the file
18.
19. int pos = strPath.find_last_of('\\', strPath.length());
20. return strPath.substr(0, pos); // Return the directory without the file name
21. }
22.
23. int _tmain(int argc, _TCHAR* argv[])
24. {
25. string strProgramDir = GetProgramDir();
26. cout<<strProgramDir<<endl;
27.
28. return 0;
29. }