QTextStream类提供了一个方便的接口来读写文本,可以在QIODevice,QByteArray和QString上进行操作。可以方便的读写单词,行和数字。对于生成文本,QTextStream对字段填充,对齐和数字格式提供了格式选项支持。可以使用构造函数,setDevice或者setString来设置QTextStream要操作的设备或者字符串。
seek定位到指定位置。
atEnd判断是否还有可以读取的数据。
flush清空写缓冲区的所有数据,并且调用设备的flush函数。
在内部,其使用了一个基于unicode的缓冲区,QTextStream使用QTextCodec来自动支持不同的字符集。默认的 ,使用QTextCodec::codeForLocal返回的编码来进行读写,也可以使用setCodec函数来设置编码。
readLine读取一行
readAll读取所有
读取单词,以空格分隔
一个一个字符读取
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QStringList>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//写入文件
QFile myFile("log.txt");
if(!myFile.open(QIODevice::WriteOnly))
{
qDebug()<<myFile.errorString();
}
QTextStream textStream(&myFile);
textStream<<"this is first line.\r\n";
textStream<<"this is second line.\r\n";
textStream<<"this is third line.\r\n";
textStream.flush();
myFile.close();
//读取文件
if(!myFile.open(QIODevice::ReadOnly))
{
qDebug()<<myFile.errorString();
}
textStream.setDevice(&myFile);
while(!textStream.atEnd())
{
QString str1 = textStream.readLine();//每次读取一行
qDebug()<<str1;
}
textStream.seek(0);
QString strAll = textStream.readAll();//全部读取
qDebug()<<strAll;
//每一次读取一个单词,过滤掉空格
textStream.seek(0);
while(!textStream.atEnd())
{
QString str;
textStream>>str;
qDebug()<<str;
}
//每一次读取一个字节
textStream.seek(0);
while(!textStream.atEnd())
{
textStream.skipWhiteSpace();
QString str = textStream.read(1);
qDebug()<<str;
}
myFile.close();
return a.exec();
}