Qt設定為GBK/System編碼時,QString轉char*亂碼問題
阿新 • • 發佈:2019-01-07
這個問題以前遇到過,結果後來忘了,今天遇到中文路徑用FILE寫檔案,結果檔名亂碼。
(我服了,這個破線上編輯器,幾段文字我格式折騰半天,還把網頁卡死兩次)。
錯誤方式:
//QString str=QString::fromLocal8Bit("中文");
//const char* cstr=str.toStdString().c_str();
//這樣qDebug可以打印出來,但寫檔案是亂碼
QString轉換char*正確方式:
QString str=QString::fromLocal8Bit("中文");//我QtCreator本地設定的是System/GBK
QByteArray arr= str.toLocal8Bit(); //我不知道為嘛非要有中間變數,搞得我一直沒弄對
onst char *cstr = arr.data();//這樣雖然qDebug()列印是問號,但是可以正常用了
FILE *fp;
fp=fopen(cstr,"w+");
char arr[]="test";
fwrite(arr,strlen(arr),1,fp);
fclose(fp);