ツールクラスCToolsは文字符号化変換と現在のパスの取得を実現する
9823 ワード
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, 0, NULL, NULL);
char* buffer = new char[stringLength + 1];
::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, 0);
wchar_t* wszString = new wchar_t[wcsLen + 1];
::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, 0, NULL, NULL);
char* buffer = new char[stringLength + 1];
::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, 0);
wchar_t* wszString = new wchar_t[wcsLen + 1];
::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(0,nPos);
}