写入文本容易,但是读入文本确实一个挑战,因为文本数据从根本上说就是含糊不清的。
例如写入"a"、"dog" :out<<"a"<<"dog';
却读入"adog" :in>>str1>>str2; str1="adog",str2=""什么也没读到。
(一)
对于复杂的文件格式,成熟的解析器是必须的!
有三种读取方法:
(1)逐行读取
QTextStream::readLine()
(2)采用16位的QChar单元,逐个字符的读取!当然,要考虑换行符、制表符和空格。这个很精确,但相当麻烦。
(3)不考虑内存的开销,在文件较小的情况下,可以一次性读完。
QTextStream::readAll()
下面采用第三种方法测试:
(二)测试代码
记得添加中文支持:
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForCStrings(codec);否者中文乱码!
#include <QCoreApplication>
#include<QTextStream>
#include<QFile>
#include<QTextCodec>
#include<iostream>
#include<QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForCStrings(codec);
QFile file("test.txt");
if(!file.open(QIODevice::WriteOnly))
{
std::cerr<<"can not open test.txt:"<<file.errorString().toStdString()<<endl;
}
QTextStream out(&file);
QString str("there is a saying goes :\r\n淡泊以明志,宁静以致远!");
out<<str;
file.close();
QFile file_in("test.txt");
if(!file_in.open(QIODevice::ReadOnly))
{
std::cerr<<"can not open test.txt:"<<file.errorString().toStdString()<<endl;
}
QTextStream in(&file_in);
QString str1;
str1=in.readAll();
qDebug()<<str1<<endl;
return a.exec();
}
(三)测试结果
1、保存到本地文档
2、从本地文档读取
(四)拓展
《C++ GUI QT 4》中利用readLine()函数先读取一行,再调用split(‘ ’)函数利用空格将QString拆分为QStringList,这样就可以获取一个个单词,也可借用join()函数再度组合。这个方法提供了很大的灵活性,值得关注。
QTextStrem in(&file);
while(!file.atEnd())
{
QString line = in.readLine();
QStringList strlist = line.split(' ');
int a = strlist.takeFirst();
QString str1 = strlist.takeFirst();
QString str2 = strlist.join("+");
}