






把Qtring 和 浮点类型的数据保存到文件,使用QFile的 write方式很麻烦,但使用使用辅助类 QTextStream 和 QDataStream就很简单
#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();
}
#include <QtCore/QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDataStream>
#include <QDebug>
void text_stream_test(QString f)
{
QFile file(f);
if( file.open(QIODevice::WriteOnly | QIODevice::Text) )
{
QTextStream out(&file);
out << QString("D.T.Software") << endl;
out << QString("Result: ") << endl;
out << 5 << '*' << 6 << '=' << 5 * 6 << endl;
file.close();
}
if( file.open(QIODevice::ReadOnly | QIODevice::Text) )
{
QTextStream in(&file);
while( !in.atEnd() )
{
QString line = in.readLine();
qDebug() << line;
}
file.close();
}
}
void data_stream_test(QString f)
{
QFile file(f);
if( file.open(QIODevice::WriteOnly) )
{
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_7);
out << QString("D.T.Software");
out << QString("Result: ");
out << 3.14; //QDataStream类型不需要 endl(换行符),QTextStream需要换行符
file.close();
}
if( file.open(QIODevice::ReadOnly) )
{
QDataStream in(&file);
QString dt = "";
QString result = "";
double value = 0;
in.setVersion(QDataStream::Qt_4_7);
in >> dt;
in >> result;
in >> value;
file.close();
qDebug() << dt;
qDebug() << result;
qDebug() << value;
}
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
text_stream_test("C:/Users/hp/Desktop/text.txt");
data_stream_test("C:/Users/hp/Desktop/data.dat");
return a.exec();
}
这篇博客介绍了如何利用QTextStream和QDataStream简化将Qtring及浮点类型数据写入文件的过程,对比了使用QFile write方法的复杂性。

被折叠的 条评论
为什么被折叠?



