环境:win10,Qt5.9.7 + msvc2017
问题:读bin文件时,发现出现丢失字节,且为固定字节0x0d,后查阅Qt帮助得知因为文件打开方式包含QIODevice::Text。
Constant |
Description |
QIODevice::Text |
When reading, the end-of-line terminators are translated to '\n'. When writing, the end-of-line terminators are translated to the local encoding, for example '\r\n' for Win32. |
QIODevice::Text的描述为:读取时,行尾终止符转换为'\n'。写入时,行尾终止符转换为本地编码,例如用于win32的'\r\n'。
后面针对两种情况做了测试。
写入代码:
QString path = QDir::currentPath() + "/test.txt";
QFile file(path);
if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
{
qDebug() << "write open file failed";
return;
}
QByteArray array;
array.clear();
char temp = 13;
array.append(temp);
temp = 10;
array.append(temp);
temp = 1;
array.append(temp);
temp = 12;
array.append(temp);
QTextStream in(&file);
in.setCodec(QTextCodec::codecForName("UTF-8"));
in<<array;
file.close();
按顺序写入0x0d,0x0a,0x01,0x0c;
读取代码:
QString xmlfilepath = QFileDialog::getOpenFileName(this, tr("Open XML File"), QDir::currentPath(), "*.txt");
QFile tagfile(xmlfilepath);
if(!tagfile.open(QIODevice::ReadOnly ))
{
qDebug() << "(read)Open Tag.csv file failed !";
return ;
}
QTextStream out(&tagfile);
out.setCodec(QTextCodec::codecForName("GB18030"));
QString str = out.readAll();
//QByteArray array = tagfile.readAll();
tagfile.close();
qDebug() << str;
不带QIODevice::Text读取结果如下:
"\r\r\n\u0001\f"
会比理论写入多一个'\r'字符。
带QIODevice::Text读取结果如下:
"\n\u0001\f"
会将字符'\r'也就是字节0x0d丢掉。
补充:
字符 | 描述 | 值 |
\n | 换行(LF) | 10 |
\f | 换页(FF) | 12 |
\r | 回车(CR) | 13 |