共享模式_fsopen打开文件失败的解决方案(实现_fsopen支持中文的方法)
程序员文章站
2022-06-04 13:02:51
...
文件打开函数如下:
void KeyManager::openKeyFile()
{
QDateTime dateTime = QDateTime::currentDateTime();
keyPath = QString(configure.keyPath.c_str()) + "/" + dateTime.toString("yyyyMMddhhmmss") + ".key";
qDebug() << "keyFilePath"<<keyPath;
qDebug()<<"keyFile1"<<keyFile;
QMutexLocker locker(&keyFileMutex);
if(keyFile != nullptr) {
fclose(keyFile);
keyFile = nullptr;
}
#if defined(_WIN32)
//keyFile = _fsopen(keyPath.toStdString().c_str(), "wb+", _SH_DENYNO);//只支持英文路径
keyFile = _wfsopen((reinterpret_cast<const wchar_t *>(keyPath.utf16())), s2ws("wb+").c_str(), _SH_DENYNO);//支持中英文路径
#else
keyFile = fopen(fileName.toStdString().c_str(), "wb+");
#endif
qDebug()<<"keyFile2"<<keyFile;
_keyOffset = 0;
_keySize = 0;
if(keyFile != nullptr) {
logger.info(u8"**文件创建成功");
}
else {
logger.error(u8"**文件创建失败");
}
}
分析如下:
1.使用_fsopen()时,在中文文件路径下,打印显示打开文件失败,如下:
keyFilePath “C:/Users/Administrator/Desktop/**/20191211145043.key”
keyFile1 0x0
keyFile2 0x0
2.使用_wfsopen()时,在中文文件路径下,打印显示打开文件失成功,如下:
keyFilePath “C:/Users/Administrator/Desktop/**/20191211160938.key”
keyFile1 0x0
keyFile2 0x473b398
3.函数里使用的类型转换如下:
QString转wchar_t*的方法
const wchar_t* wstr = reinterpret_cast<const wchar_t *>(filename.utf16());
wstring转换为string:
std::string ws2s(const std::wstring& ws)
{
std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "chs");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
memset(_Dest,0,_Dsize);
wcstombs(_Dest,_Source,_Dsize);
std::string result = _Dest;
delete []_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
string转换为wstring:
std::wstring s2ws(const std::string& s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete []_Dest;
setlocale(LC_ALL, "C");
return result;
}
下一篇: linux Shell常用命令笔记