《C++避坑神器·十四》项目路径获取及WCHAR 和char* 的相互转换

本文介绍了如何使用C++在Windows环境中获取DLL路径、当前工程目录、解决方案.sln文件路径以及.exe文件路径,并提到了WCHAR和char之间的转换注意事项。

📢博客主页: 主页
📢欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正!
📢本文由 梦回阑珊 原创,首发于 优快云,转载注明出处🙉
📢代码改变世界,你来改变代码!✨

在这里插入图片描述

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;
}
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦回阑珊

一毛不嫌多,一分也是爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值