共享模式_fsopen打开文件失败的解决方案(实现_fsopen支持中文的方法)

文件打开函数如下:

void KeyManager::openKeyFile()
{
QDateTime dateTime = QDateTime::currentDateTime();
keyPath = QString(configure.keyPath.c_str()) + "/" + dateTime.toString("yyyyMMddhhmmss") + ".key";

qDebug() << "keyFilePath"<(keyPath.utf16())), s2ws("wb+").c_str(), _SH_DENYNO);//支持中英文路径
#else
keyFile = fopen(fileName.toStdString().c_str(), "wb+");
#endif
qDebug()<<"keyFile2"<

分析如下:
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(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;
}

你可能感兴趣的:(C/C++,标准库)