1、文本流设置unicode小端模式
2、写入文本前两个字节FF FE
3、字符串转成unicode编码
QList<QByteArray> list = QTextCodec::availableCodecs();
//可以获取Qt支持的编码,下面列出字符串的几种编码名称
//GBK GB2312
//unicode 小端
//UTF-8
//UnicodeLitteUnmarked 小端
//UnicodeBigUnmarked 大端
- #include <QApplication>
- #include <QFile>
- #include <QTextStream>
- #include <QTextCodec>
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- // Widget w;
- // w.show();
- QFile fielWrite("a.txt");
- if (!fielWrite.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Truncate))
- {
- return 0;
- }
- QTextStream out(&fielWrite);
- out.setCodec(QTextCodec::codecForName("unicode"));//unicode小端模式
- //out.setAutoDetectUnicode(true); //好像没用处
- QChar head = 0xfeff;//unicode文件头 文本里前两个字节为FFFE
- out << head;
- QString str = "我";//"我"在Qt文本编辑器里默认是UTF-8编码格式,转成QString之后为unicode编码
- out << str;
- fielWrite.close();
- return a.exec();
- }
http://blog.csdn.net/bladeandmaster88/article/details/54868654
在qt5.9中,使用
out.setCodec(QTextCodec::codecForName("unicode"));//unicode小端模式
无法输出unicode的txt文件,需要改为:
out.setCodec("UTF-16");
详细请见qt帮助文档
----------------------------------------------------------------------------------------------------------------
QList<QByteArray> list = QTextCodec::availableCodecs();
qDebug() << list;
UTF-8
ISO-8859-1
latin1
CP819
IBM819
iso-ir-100
csISOLatin1
ISO-8859-15
latin9
UTF-32LE
UTF-32BE
UTF-32
UTF-16LE
UTF-16BE
UTF-16
System
Big5-HKSCS
Big5
Big5-ETen
CP950
windows-949
CP949
EUC-KR
Shift_JIS
SJIS
MS_Kanji
ISO-2022-JP
JIS7
EUC-JP
GB2312
GBK
CP936
MS936
windows-936
GB18030
hp-roman8
roman8
csHPRoman8
TIS-620
ISO 8859-11
WINSAMI2
WS2
macintosh
Apple Roman
MacRoman
windows-1258
CP1258
windows-1257
CP1257
windows-1256
CP1256
windows-1255
CP1255
windows-1254
CP1254
windows-1253
CP1253
windows-1252
CP1252
windows-1251
CP1251
windows-1250
CP1250
IBM866
CP866
csIBM866
IBM874
CP874
IBM850
CP850
csPC850Multilingual
ISO-8859-16
iso-ir-226
latin10
ISO-8859-14
iso-ir-199
latin8
iso-celtic
ISO-8859-13
ISO-8859-10
iso-ir-157
latin6
ISO-8859-10:1992
csISOLatin6
ISOtΰP