获取exe所在路径及几个字符串函数转换总结

 TCHAR exeFullPath[MAX_PATH];
 GetModuleFileName(NULL, exeFullPath, MAX_PATH);
/*格式转换*/
string FilePath = WCharToMByte(exeFullPath);
/*去掉exe的名称得到路径*/
string FileNamePath = FilePath.substr(0, FilePath.find_last_of("\\") + 1);
/*TCHAR[]->string*/
string WCharToMByte(LPCWSTR lpcwszStr)
{
    
    
    string str;
    DWORD dwMinSize = 0;
    LPSTR lpszStr = NULL;
    dwMinSize = WideCharToMultiByte(CP_OEMCP, NULL, lpcwszStr, -1,
        NULL, 0, NULL, FALSE);
    if (0 == dwMinSize)
    {
    
    
        return "";
    }
    lpszStr = new char[dwMinSize];
    WideCharToMultiByte(CP_OEMCP, NULL, lpcwszStr, -1, lpszStr, dwMinSize,
        NULL, FALSE);
    str = lpszStr;
    delete[] lpszStr;
    return str;
}
/*wstring->string*/
string ws2s(wstring& ws)
{
    
    
    _bstr_t t = ws.c_str();
    char* pchar = (char*)t;
    string result = pchar;
    return result;
}

/*string->wstring*/
wstring s2ws(string& s)
{
    
    
    _bstr_t t = s.c_str();
    wchar_t* pwchar = (wchar_t*)t;
    wstring result = pwchar;
    return result;
}

//UTF-8转为GBK2312 
char* UtfToGbk(const char* utf8)
{
    
    
	int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[len + 1];
	memset(wstr, 0, len + 1);
	MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
	len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
	char* str = new char[len + 1];
	memset(str, 0, len + 1);
	WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
	if(wstr) delete[] wstr;
	return str;
}

std::string TF8Tostring(std::string& str)
{
    
    
	int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
	wchar_t* pwBuf = new wchar_t[nwLen + 1];
	memset(pwBuf, 0, nwLen * 2 + 2);
	MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);
	char* pBuf = new char[nLen + 1];
	memset(pBuf, 0, nLen + 1);
	WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);
	std::string retStr = pBuf;
	delete[]pBuf;
	delete[]pwBuf;
	pBuf = NULL;
	pwBuf = NULL;
	return retStr;
}

猜你喜欢

转载自blog.csdn.net/qq_38158479/article/details/120175384