唐老师代码如下:
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QFile file("C:/Users/hp/Desktop/test.hex");
if( file.open(QIODevice::WriteOnly) )
{
QString dt = "D.T.Software";
double value = 3.14;
file.write(dt.toStdString().c_str());
file.write(reinterpret_cast<char*>(&value), sizeof(value));
file.close();
}
if( file.open(QIODevice::ReadOnly) )
{
QString dt = "";
double value = 0;
dt = QString(file.read(12));
file.read(reinterpret_cast<char*>(&value), sizeof(value));
file.close();
qDebug() << dt;
qDebug() << value;
}
return a.exec();
}
其中的将字符串写进二进制文件的用法,在Qtcreator4.5.1中没实现的了。
查阅资网上信息后,将代码改为:
if( file.open(QIODevice::WriteOnly) )
{
QString dt = "willwilling";
double value = 3.14;
file.write( dt.toLatin1() );
file.write(reinterpret_cast<char*>(&value), sizeof(value) );
file.close();
}
输出正常。
toLatin1():
QByteArray QString::toLatin1 () const
Returns a Latin-1 representation of the string as a QByteArray.
The returned byte array is undefined if the string contains non-Latin1 characters. Those characters may be suppressed or replaced with a question mark.
See also fromLatin1(), toAscii(), toUtf8(), toLocal8Bit(), and QTextCodec.
Latin1是ISO-8859-1的别名,有些环境下写作Latin-1。ISO-8859-1编码是单字节编码,向下兼容ASCII,其编码范围是0x00-0xFF,0x00-0x7F之间完全和ASCII一致,0x80-0x9F之间是控制字符,0xA0-0xFF之间是文字符号。