Qt 文本流QTextStream

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();
}

 

  • 13
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值