QTextStream读写文件

最好不要用QTextStream读文件,因为它会自动把文本当成字符串

#include "widget.h"
#include "ui_widget.h"
#include 
#include 
#include 
#define cout qDebug()<<"["<<__FILE__<<":"<<__LINE__<<"]"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    writeData();
    readData();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::writeData()
{
    QFile file;
    file.setFileName("C:/Users/kihay/Desktop/Qt/day3/demo.txt");

    bool isOk = file.open(QIODevice::WriteOnly);
    if(true==isOk)
    {
        QTextStream stream(&file);
        //指定编码
        stream.setCodec("UTF-8");
        stream<<QString("你猜")<<250;

        file.close();
    }

}

void Widget::readData()
{
    QFile file;
    file.setFileName("C:/Users/kihay/Desktop/Qt/day3/demo.txt");

    bool isOk = file.open(QIODevice::ReadOnly);
    if(true==isOk)
    {
        QTextStream stream(&file);
        //指定编码,前面以什么编码写,后面最好以什么编码读
        stream.setCodec("UTF-8");
        QString str;
        int a;
        stream >>str>>a;
        cout<<str<<a;
        file.close();
    }
}

输出是:[ …\09_QTextStream\widget.cpp : 54 ] “你猜250” 0

你可能感兴趣的:(QTextStream读写文件)