工具类CTools实现字符编码转换和获取当前路径

时间:2024-03-21 16:36:02
class CTools
{
public:
CTools(void);
public:
~CTools(void);
public:
static std::string UNICODE_to_UTF8(const CString& unicodeString);
static CString UTF8_to_UNICODE(const std::string& utf8_string);
static std::string ws2s(std::wstring& inputws);
static std::wstring s2ws(const std::string& s); static std::string UNICODE_to_ANSI(const CString& unicodeString);
static CString ANSI_to_UNICODE(const std::string& utf8_string); static std::string GetFullPath(void);
}; CTools::CTools(void)
{
} CTools::~CTools(void)
{
} std::string CTools::UNICODE_to_UTF8(const CString& unicodeString)
{
int stringLength = ::WideCharToMultiByte(CP_UTF8, NULL, unicodeString, (int)wcslen(unicodeString), NULL, , NULL, NULL); char* buffer = new char[stringLength + ];
::WideCharToMultiByte(CP_UTF8, NULL, unicodeString, (int)wcslen(unicodeString), buffer, stringLength, NULL, NULL);
buffer[stringLength] = '\0'; std::string str = buffer; delete[] buffer; return str;
} CString CTools::UTF8_to_UNICODE(const std::string& utf8_string)
{
int length = (int)utf8_string.size(); int wcsLen = ::MultiByteToWideChar(CP_UTF8, NULL, utf8_string.c_str(), length, NULL, );
wchar_t* wszString = new wchar_t[wcsLen + ];
::MultiByteToWideChar(CP_UTF8, NULL, utf8_string.c_str(), length, wszString, wcsLen);
wszString[wcsLen] = '\0';
CString unicodeText(wszString);
delete[] wszString; return unicodeText;
} std::string CTools::UNICODE_to_ANSI(const CString& unicodeString)
{
int stringLength = ::WideCharToMultiByte(CP_ACP, NULL, unicodeString, (int)wcslen(unicodeString), NULL, , NULL, NULL); char* buffer = new char[stringLength + ];
::WideCharToMultiByte(CP_ACP, NULL, unicodeString, (int)wcslen(unicodeString), buffer, stringLength, NULL, NULL);
buffer[stringLength] = '\0'; std::string str = buffer; delete[] buffer; return str;
} CString CTools::ANSI_to_UNICODE(const std::string& utf8_string)
{
int length = (int)utf8_string.size(); int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, utf8_string.c_str(), length, NULL, );
wchar_t* wszString = new wchar_t[wcsLen + ];
::MultiByteToWideChar(CP_ACP, NULL, utf8_string.c_str(), length, wszString, wcsLen);
wszString[wcsLen] = '\0';
CString unicodeText(wszString);
delete[] wszString; return unicodeText;
} std::string CTools::ws2s(std::wstring& inputws)
{
return UNICODE_to_UTF8(inputws.c_str());
} std::wstring CTools::s2ws(const std::string& s)
{
CString cstr = UTF8_to_UNICODE(s);
return cstr.GetBuffer(cstr.GetLength());
} std::string CTools::GetFullPath(void)
{
HMODULE h = GetModuleHandle(L"Test.exe");
wchar_t exeFullPath[MAX_PATH]; // MAX_PATH在API中有定义,为128
int len=GetModuleFileName(h,
exeFullPath, //应用程序的全路径存放地址
MAX_PATH);
std::wstring wstrpath = exeFullPath;
std::string strpath = CTools::ws2s(wstrpath);
size_t nPos;
nPos=strpath.rfind('\\');
return strpath.substr(,nPos);
}