Windows环境下的C++获取当前程序的exe文件路径

来源:互联网 发布:兵器科学与技术 知乎 编辑:程序博客网 时间:2024/05/16 10:05

获取.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.      char exeFullPath[MAX_PATH]; // Full path   

10.    string strPath = "";   

11.   

12.    GetModuleFileName(NULL,exeFullPath,MAX_PATH);   

13.     strPath=(string)exeFullPath;    // Get full path of the file   

14.  

15.     int pos = strPath.find_last_of('\\', strPath.length());   

16.    return strPath.substr(0, pos);  // Return the directory without the file name   

17. }      

18.  

19. int _tmain(int argc, _TCHAR* argv[])  

20.{   

21.     string strProgramDir = GetProgramDir();  

22.    cout<<strProgramDir<<endl;  

23.   

24.    return 0;  

25.

 Unicode字符集环境下

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. }  

 

 

阅读全文
0 0
原创粉丝点击