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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM