Qt解析QTextStream及QDataStream

QTextStream及QDataStream

异同点

首先来谈谈QTextStream和QDataStream的共同点:QTextStream和QDataStream都是对流进行操作
再来谈谈区别吧:QTextStream只能普通类型的流操作像QChar、QString、int…,其实就很类似我们c或者c++中读写文件的感觉,而QDataStream就厉害了,无论是QTextStream的普通类型的流操作还是一些特殊类型的流操作它都可以办的到比如:QFont、QPoint、QDate之类的几乎所有Qt中支持的所有类型都可以用QDataStream来进行操作,再比如我下面这格代码:


QFile file("binary.bat");
    if(file.open(QIODevice::WriteOnly|QIODevice::Truncate)){
        //QTextStream out(&file);
        int age=18;
        out<<QString("周杰伦")
           <<QDate::fromString("2000-11-18","yyyy-MM-dd")
           <<age;
        file.close();
    }

它存在错误:

1、.QTextStream不能用来操作QDate类型

QDataStream

	//写文件
    QFile file("binary.bat");
    if(file.open(QIODevice::WriteOnly|QIODevice::Truncate)){
        QDataStream out(&file);
        int age=18;
        out<<QString("周杰伦")
           <<QDate::fromString("2000-11-18","yyyy-MM-dd")
           <<age;
        file.close();
    }else{
        file.errorString();
    }

    //读文件
    if(file.open(QIODevice::ReadOnly)){
        QDataStream in(&file);
        QString name;
        QDate birth;
        int age;
        in>>name>>birth>>age;
        qDebug()<<"姓名:"<<name
                <<"出生日期:"<<birth
                <<"年龄:"<<age;
    }else{
    	qDebug()<<file.errorString();
    }

运行结果:
在这里插入图片描述

对于流的操作如果不会太明白的同学可以去先复习复习c中对于文件的操作,那样可能会更加清晰一些


QTextStream

  QFile file("hello.txt");
    if(file.open(QIODevice::ReadOnly)){
        char buffer[100];
        //readLine如果失败会返回-1,成功返回读取的字节数
        int n=file.readLine(buffer,sizeof(buffer));
        if(n!=-1){

            qDebug()<<"长度:"<<n<<endl
                    <<"内容:"<<buffer<<endl;
            file.close();
        }else{
            qDebug()<<file.errorString();
        }
    }else{
        qDebug()<<file.errorString();
    }

    //写文件
    if(file.open(QIODevice::WriteOnly|QIODevice::Truncate)){
        QTextStream out(&file);
        double dPI=3.1415925;
        int age=100;
        out.setFieldWidth(10);  //设置字节宽度
        out.setFieldAlignment(QTextStream::AlignLeft);  //左对齐
        out.setRealNumberPrecision(8);  //设置整数精度
//QTextStream的流操作符的使用
//        out<<bin       //二进制写入
//           <<showbase  //显示数据是几进制
//           <<age;

        out<<"PI:"<<dPI;

        file.close();
    }else{
        qDebug()<<file.errorString();
    }

运行结果
在这里插入图片描述

在这里插入图片描述
如果这篇文章哪里有勘误或者有不一样见解的地方欢迎提出来,大家共同进步,感谢😘

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值