QTextStream QFile 实时输出到文件

    在对文件操作的时候,我们都知道QFile,那么QTextStream是干嘛用的呢?查询帮助文档我们可以知道,QTextStream 提供了一个快捷的接口来读写文件,可以提供相当多的格式,对齐方式。

那么怎么使用呢?比如说我们要实现下面的功能,点击“写入”就将上面的文字写入文件,点击“关闭”就将文件关闭,禁止写入。



来看头文件.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtWidgets>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_inputBtn_clicked();

    void on_clostBtn_clicked();

private:
    Ui::MainWindow *ui;

    QFile       *m_file;
    QTextStream *m_stream;

    void init();
};

#endif // MAINWINDOW_H

看.cpp,重点看注释,重点都我都写在注释里了。

#include "mainwindow.h"

#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_file = nullptr;
    m_stream = nullptr;

    init();
}

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

void MainWindow::on_inputBtn_clicked()
{
    QString str = ui->plainTextEdit->toPlainText(); //去读界面上输入的文字

    if(m_stream != nullptr)
    {
        *m_stream << str << "\r\n";       // 将数据写入到数据流中,注意是带*
        m_stream->flush();                //将数据流中的数据写到文件,如果没有这一步,就不会马上写入到文件中。有了这一步就不用每次都打开与关闭文件了
    }
}

void MainWindow::init()
{
    QString filePath = qApp->applicationDirPath() + "/log.txt";

    m_file = new QFile(filePath);
    m_stream = new QTextStream(m_file); //用法

    m_file->open(QIODevice::WriteOnly | QIODevice::Append); //只写 与 添加 打开

}

void MainWindow::on_clostBtn_clicked()
{
    if(m_file != nullptr)
    {

        m_file->close();
        delete m_file;
        m_file = nullptr;
    }

    if(m_stream != nullptr)
    {
        delete m_stream;
        m_stream = nullptr;
    }


}

上面的demo可以下载:demo下载


猜你喜欢

转载自blog.csdn.net/xiezhongyuan07/article/details/79995128
今日推荐