0
votes

I try to read and write from same file but get strange behavior. Here is example code :

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTextStream>
#include <QFile>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void on_textEdit_textChanged();

private:
    QFile *File;
    QTextStream *FileStream;
    QString TextFromFile;
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

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

    File = new QFile;
    File->setFileName("test.txt");
    File->open(QIODevice::ReadWrite | QIODevice::Text);
    FileStream = new QTextStream(File);

    TextFromFile = FileStream->readAll();
    ui->textEdit->setText(TextFromFile);

    File->close();
    File->open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text);
}

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

void MainWindow::on_textEdit_textChanged()
{
    *FileStream << ui->textEdit->toPlainText();
    FileStream->flush();
}

So when i type for example this :
enter image description here
file will change to this :
enter image description here
but i need this :
enter image description here
My aim is to overwrite file every time when i type characters to textedit.

1
There's no "strange behavior" here at all, this is what you'd expect a stream operator to do.MrEricSir
@MrEricSir, Can you explain, please?ratojakuf
This was the 37000th question in the qt tag.lpapp

1 Answers

3
votes

If you need rewrite file every time then try to do this without pointers. Something like:

void MainWindow::on_textEdit_textChanged()
{    
    QElapsedTimer timer;
    timer.start();  
    QFile file("test.txt");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        qDebug() << "failed open";
    else
    {
        QTextStream out(&file);
        out << ui->textEdit->toPlainText();
    }
    qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
}

QFile destructor will close file at the end of slot.

Output in my case:

The slow operation took 0 milliseconds 
The slow operation took 0 milliseconds 

Of course with big data it will be slower, but I think that it is normal approach.

Probably you thought that QIODevice::Truncate should do the trick, but it is wrong. From doc:

If possible, the device is truncated before it is opened. All earlier contents of the device are lost.

But in your code it does not work because you use same stream, you does not open your file every time, you just append new words every time. And flush() just flushes any buffered data waiting to be written to the device.