strig
strig

Reputation: 3

Trying to open and read a .txt file, but it deletes the actual text from the original file (Qt GUI C++

I am trying to open and read a .txt file and then show one line of it in a label, and the line is not showing but everything is deleted from the original selected file. Any idea?

{
    QString filename = QFileDialog::getOpenFileName(this,
                                                    tr("Open File"),
                                                    "/Users/kat/Documents/Programming 2/Assignment/Quizzes",
                                                    "All Files (*.*);;Text File (*.txt)");
    QFile file(filename);

    if(!file.open(QFile::WriteOnly | QFile::Text))
    {
        QMessageBox::warning(this, tr("File Not Open"),"File Cannot Be Opened");
    }

    QTextStream in(&file);
    QRegularExpression re("Name: ");
    QString title = in.readLine();
    title.remove(re);
    ui->label_4->setText(title);
    file.flush();
    file.close();```

Upvotes: 0

Views: 71

Answers (1)

Lyudmila
Lyudmila

Reputation: 71

You have opened file for writing instead of reading if(!file.open(QFile::WriteOnly | QFile::Text)). If you need to read a file, you shouldn't do file.flush().

Upvotes: 1

Related Questions