POCO识别UTF8编码的字符串,所以直接用含有中文字符的C++字符串初始化Poco::Path或Poco::File是找不到文件路径的
同时Poco::File获取的文件名称也是UTF8编码的,C++输出为乱码,需将UTF8字符串转码
代码:
//! 将C++字符转为UTF8编码,主要用于Poco中文路径
/*!
\param[in] str 需要转换的C++字符串
\return UTF8编码的字符串
*/
std::string strtoUTF8(const char* str)
{
#if defined (POCO_WIN32_UTF8)
std::string s = str;
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
Poco::UTF16Char *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest, _Source, _Dsize);
Poco::UTF16String result = _Dest;
delete []_Dest;
setlocale(LC_ALL, "C");
std::string utf8str;
Poco::UnicodeConverter::convert(result, utf8str);
return utf8str;
#else
return str;
#endif
}
//! 将UTF8编码的字符串转为C++字符串,主要用于输出Poco中文路径
/*!
\param[in] str8 需要转换的UTF8编码的字符串
\return C++字符串
*/
std::string UTF8toStr(std::string str8)
{
#if defined (POCO_WIN32_UTF8)
setlocale(LC_ALL, "chs");
Poco::UTF16String str16;
Poco::UnicodeConverter::convert(str8, str16);
Poco::UTF16Char * char16 = (Poco::UTF16Char*)str16.c_str();
size_t _Dsize = (str16.size() + 1) * 2;
char * char8 = (char*)malloc(_Dsize);
memset(char8, 0, _Dsize);
wcstombs(char8, char16, _Dsize);
std::string str = char8;
delete[]char8;
setlocale(LC_ALL, "C");
return str;
#else
return str8;
#endif
}
调用:
char * _str = "D:\\test路径测试\\";
Poco::Path _path(str2UTF8(_str));
std::string _str2 = UTF82Str(_path.getFileName());