1、获取当前DLL路径
char* getCurPath() { CString path; TCHAR curPath[MAX_PATH] = { 0 }; GetModuleFileName(GetModuleHandle(0), curPath, MAX_PATH); int index = CString(curPath).ReverseFind('\\'); if (index > 0) { path = CString(curPath).Left(index + 1); } int len = WideCharToMultiByte(CP_ACP, 0, path, -1, NULL, 0, NULL, NULL); char* ptxtTemp = new char[len + 1]; WideCharToMultiByte(CP_ACP, 0, path, -1, ptxtTemp, len, NULL, NULL); return ptxtTemp; }
2、获取当前工程所在目录的绝对路径
char buf[256]; WCHAR wszClassName[256]; memset(wszClassName, 0, sizeof(wszClassName)); MultiByteToWideChar(CP_ACP, 0, buf, strlen(buf) + 1, wszClassName, sizeof(wszClassName) / sizeof(wszClassName[0])); GetCurrentDirectory(1000, wszClassName);
特别注意:string在遇到GetCurrentDirectory函数时不能重新赋值,总是报一些奇怪的错误,所以不要把string和GetCurrentDirectory连用,可以用char*代替string。
3、获取解决方案.sln文件路径
#include <windows.h> #include <direct.h> #define GetCurrentDir _getcwd std::string get_current_dir() { char buff[FILENAME_MAX]; // create string buffer to hold path GetCurrentDir(buff, FILENAME_MAX); string current_working_dir(buff); return current_working_dir; }
4、获取exe或debug路径
#include <windows.h> std::string get_exe_dir() { char szFilePath[MAX_PATH + 1] = { 0 }; GetModuleFileNameA(NULL, szFilePath, MAX_PATH); (strrchr(szFilePath, '\\'))[0] = 0; string str_path = szFilePath; return str_path; }
5、WCHAR 和char 的相互转换*
void wchar2strstring(std::string & szDst,WCHAR * wchart) { wchar_t * wtext = wchart; DWORD dwNmu = WideCharToMultiByte(CP_OEMCP,NULL,wtext,-1,NULL,0, NULL,FALSE); char * psTest; psTest = new char[dwNmu]; WideCharToMultiByte(CP_OEMCP, NULL, wtext, -1, psTest, dwNmu, NULL, FALSE); szDst = psTest; delete[]psTest; }
wchar_t* trstring2wchar( const char *str) { int mystringsize = (int)(strlen(str) + 1); WCHAR* wchart = new wchar_t[mystringsize]; MultiByteToWideChar(CP_ACP,0, str,-1,wchart,mystringsize); return wchart; }