QTextStream 的简单理解

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();
}
  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值