文章目录
QTextStream 的简单理解
QTextStream类提供了使用QIODevice读写文本的基本功能。
QTextStream可以操作QIODevice上,支持QByteArray和QString。如果使用QTextStream的operators,可以方便的读写words,lines 和numbers. 对一般的文本,QTextStream支持格式化对齐,格式化数字 等。例如
QFile data(“output.txt”);
if (data.open(QFile::WriteOnly | QFile::Truncate)) {
QTextStream out(&data);
out << "Result: " << qSetFieldWidth(10) << left << 3.14 << 2.7;
// writes "Result: 3.14 2.7 "
}
还有一种通常的用法就是控制台命令的读写
,例如:
QTextStream stream(stdin);
QString line;
while (stream.readLineInto(&line)) {
…
}
除了QTextStream的构造函数,还要常用的一些方法
,例如:
setDevice() : 设置设备
setString(): 设置字符串
seek():查找位置
atEnd():返回是否还有数据可读
flush():清空写缓存区
QTextStream 使用的是Unicode 缓存,Qt中的QTextCodec类 可以支持各种字符集。
通常有三种方式来读文本文件
:
- chunk By chunk(块读):readLine()和readAll()
- Word By Word(按字读):
- character By character(按字节读):
Qt提供了几个和iostream相似的全局函数:
bin设置QTextStream来读/写二进制数字
-oct设置QTextStream来读/写八进制数字
-dec设置QTextStream来读/写十进制数字
-hex设置QTextStream来读/写十六进制数字
-endl强制换行
-flush强制QIODevice刷新任何被缓存的数据
-ws作为任何可用的控制符(在输入的时候)
-reset重新设置QTextStream为它的缺省模式(请见reset())
-qSetW(int)设置字段宽度作为指定参数
-qSetFill(int)设置填充字符作为指定参数
-qSetPrecision(int)设置精确度作为指定参数
简单示例:
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();
}