📢博客主页: 主页
📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
📢本文由 梦回阑珊 原创,首发于 优快云,转载注明出处🙉
📢代码改变世界,你来改变代码!✨
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;
}
本文介绍了如何使用C++在Windows环境中获取DLL路径、当前工程目录、解决方案.sln文件路径以及.exe文件路径,并提到了WCHAR和char之间的转换注意事项。
2万+

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



