2012-02-29 41 views
1

如何使用Qt 4.7.2將字符數組寫入使用CP-1251編碼的二進制文件?
使用特定編碼將字符數組寫入二進制文件

下面的代碼無法正常工作,這樣可以節省在UTF-8編碼陣列:

QTextCodec* codec = QTextCodec::codecForName("Windows-1251"); 
QTextCodec::setCodecForCStrings(codec); 

char* str = "абвгд"; 

ofstream out("/home/ivan/Binary/moo.bin"); 
out << str; 
out.close(); 



UPD:解決方案已被發現。 :>在Ubuntu 11.04

QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); // Set encoding for QObject::tr 
QTextCodec* codec = QTextCodec::codecForName("Windows-1251") ; // Set encoding for result data in file 
QByteArray bytes = codec->fromUnicode(QObject::tr("Текст на русском языке")); // Encode data in cp-1251 


// Write data to binary file 
ofstream out("/home/ivan/Binary/moo.bin", ios::out | ios::binary); 
out.write(bytes.constData(), bytes.size()); 
out.close(); 

優良工程,工程

+0

QTextCodec :: fromUnicode()其中QByteArray,你可以嘗試將其存儲到文件中。 – Kunal 2012-02-29 08:39:25

回答

0

你不在這裏使用Qt的。 QTextCodec::setCodecForCStrings決定了QString如何讀取char *,並且肯定無法控制標準庫如何選擇寫入文本。

如果你確實想用Qt來做這件事,請使用QTextStream並在其上設置合適的編解碼器。