参考资料:
http://www.cnblogs.com/fuyanwen/p/3200536.html
http://www.cnblogs.com/wendao/archive/2012/07/27/2612597.html
不能直接用:
QString szqFileName = QString::fromLocal8Bit("data");
const char* szName = szqFileName.toLocal8Bit().constData(); // 返回的 QByteArray 被析构掉了, szName 会指向无效的内存区
正确的做法:
QString szqFileName = QString::fromLocal8Bit("data");
QByteArray ba = szqFileName.toLocal8Bit();
const char* szName = ba.constData();
代码(在我的系统上, Win7 x64. CHS. 第21, 40行如果我用utf8的话就会乱码), 下载DEMO:
1 #include <iostream> 2 3 #include <Windows.h> 4 #include <QtCore/QtCore> 5 6 #ifdef UNICODE 7 #define FILE_NAME "数据.txt" 8 #else 9 #define FILE_NAME "data.txt" 10 #endif 11 12 int main() 13 { 14 QString szqFileName = QString::fromLocal8Bit(FILE_NAME); 15 qint64 nLen = szqFileName.length(); 16 // 17 // QString to TCHAR* 18 // 19 LPCTSTR szFileName = NULL; 20 #ifdef UNICODE 21 szFileName = (wchar_t*)szqFileName.utf16(); 22 #else 23 QByteArray byteArray = szqFileName.toLocal8Bit(); 24 szFileName = byteArray.constData(); 25 #endif // UNICODE 26 // 27 // Create file 28 // 29 HANDLE hFile = ::CreateFile(szFileName, GENERIC_WRITE, 0, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); 30 if (hFile == INVALID_HANDLE_VALUE) 31 std::cout << "Cannot create file." << std::endl; 32 else 33 std::cout << "File created." << std::endl; 34 ::CloseHandle(hFile); 35 // 36 // TCHAR* to QString 37 // 38 szFileName = TEXT(FILE_NAME); 39 #ifdef UNICODE 40 szqFileName = QString::fromUtf16((ushort*)szFileName); 41 #else 42 szqFileName = QString::fromLocal8Bit(szFileName); 43 #endif 44 QFile file(szqFileName); 45 if (!file.remove()) 46 std::cout << "Cannot remove file." << std::endl; 47 else 48 std::cout << "File removed." << std::endl; 49 50 return 0; 51 }
时间: 2024-10-12 22:07:01