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 :
file will change to this :
but i need this :
My aim is to overwrite file every time when i type characters to textedit.