2014-12-22 19 views
0

我嘗試讀取和寫入同一個文件,但得到奇怪的行爲。下面是示例代碼:QTextStream將錯誤的數據寫入文件

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

所以,當我鍵入例如這樣的:
enter image description here
文件將改變這個:
enter image description here
,但我需要這樣的:
enter image description here
我的目標是每次覆蓋文件時,我對文字編輯輸入的字符。

+0

這裏根本沒有「奇怪的行爲」,這是您期望流操作員所要做的。 – MrEricSir

+0

@MrEricSir,你能解釋一下嗎? – niceday

+1

這是qt標籤中的第37000個問題。 – lpapp

回答

3

如果您每次都需要重寫文件,那麼嘗試不用指針就可以做到這一點。類似於:

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析構函數將在插槽末尾關閉文件。

輸出在我的情況:

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

當然與大數據將是慢,但我認爲這是正常的做法。

也許你認爲QIODevice::Truncate應該做的伎倆,但它是錯誤的。來自doc:

如果可能,設備在打開之前會被截斷。所有較早的 設備內容都會丟失。

但在代碼中這是行不通的,因爲你用同一個流,你不打開您的每一次文件,只需每次追加新單詞。而flush()只是刷新等待寫入設備的任何緩衝數據。

+0

但是性能如何?你的變體需要更多還是不需要? – niceday

+1

我會首先擔心正確性。快速的代碼不起作用並不是那麼有用。 –

+0

順便說一下,你能解釋爲什麼我的代碼工作不正確? – niceday