Qt QTextStream 读写文件

项目目录:

widget.h:

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    void writeData();//自定义函数
    void readData();//自定义函数


private slots:
    void on_buttonRead_clicked();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

 

 

widget.cpp:

#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QTextStream>//可以指定编码

#include <QDebug>
#include <QFileDialog>

#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("../demo.txt");

    bool isOk = file.open(QIODevice::WriteOnly);
    if (isOk == true )
    {
        QTextStream stream(&file);

        //指定编码
        stream.setCodec("UTF-8");
        stream << QString("主要看气质")<<250;

        file.close();
    }
}



/*使用readData()函数的话,能够输出结果,只是输出的结果中会多出一个0;
 * 这是因为利用这种办法它并不能判断字符串的结尾,所以就将str和a当成一个字符串了,到后面要输出a的时候,
 * 里面已经没有内容了,于是就输出了0;
 * 这也说明使用这种方式读内容的话,并不安全,
 * 所以应该采用readall、readline的方式
*/
void Widget::readData()
{
    QFile file;
    file.setFileName("../demo.txt");

    bool isOk = file.open(QIODevice::ReadOnly);
    if (isOk == true )
    {
        QTextStream stream(&file);

        //指定编码
        stream.setCodec("UTF-8");

        QString str;
        int a;
        stream>>str >>a;


        cout<<str<<a;

        file.close();
    }
}


/*
 * 按照如下的方式去读取文件中的内容
 * 在ui界面中创建一个按钮和文本编辑器,并将按钮转到槽,
*/


void Widget::on_buttonRead_clicked()
{
    QString path = QFileDialog::getOpenFileName(this,"open","../");
    if (false ==path.isEmpty())
    {
        QFile file;
        file.setFileName(path);

        bool isOk = file.open(QIODevice::ReadOnly);
        if (isOk == true )
        {
            QTextStream stream(&file);

            //指定编码
            stream.setCodec("UTF-8");

            QString str = stream.readAll();
            ui->textEdit->setText(str);

            file.close();
        }
    }
}

 

posted @ 2019-07-06 16:36  Mr_Song_D  阅读(7505)  评论(0编辑  收藏  举报