I can't save .txt file with QFileDialog, C++ QT

2.2k views Asked by At

This is my code:

void MainWindow::save(){
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path, tr("Text Files (*.txt)"));
    if (fileName != "")
    {
       QFileInfo info(fileName);
       path = info.absoluteDir().absolutePath();
       QFile file(path);
       if(!file.open(QIODevice::WriteOnly)){
           QString text = ui->plainTextEdit->toPlainText();
           QTextStream out(&file);
           out << text ;
           file.close();
       }
    }
}

But it doesn't create any .txt file after click a pushButton:

connect(ui->saveButton, SIGNAL(clicked(bool)), this, SLOT(save()));

Log:

QIODevice::write (QFile, "C:\Users\kfg\Desktop"): device not open

Thanks for your help :)

1

There are 1 answers

0
Simon Kraemer On BEST ANSWER

You make 2 mistakes.

The first is here in the line path = info.absoluteDir().absolutePath(); This will give you the path of the directory, not the file. You should use path = info.absoluteFilePath();. See QFileInfo::absoluteFilePath().

The next is that you write to the "file" when open returns false (fails).

I think for your code to be correct you should use something like this:

void MainWindow::save() 
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path, tr("Text Files (*.txt)"));
    if (fileName != "")
    {
        QFile file(QFileInfo(fileName).absoluteFilePath());
        if (file.open(QIODevice::WriteOnly))
        {
            QString text = ui->plainTextEdit->toPlainText();
            QTextStream out(&file);
            out << text;
            file.close();
        }
        else
        {
            //TODO: Error message
        }
    }
}

You might also want to check whether the file already exists and ask the user if it is ok to overwrite it...

void MainWindow::save() 
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Text File"), path, tr("Text Files (*.txt)"));
    if (fileName != "")
    {
        QFile file(QFileInfo(fileName).absoluteFilePath());

        if (file.exists())
        {
            QMessageBox::StandardButton chosenButton 
                = QMessageBox::warning(this, tr("File exists"), tr("The file already exists. Do you want to overwrite it?"), 
                    QMessageBox::Ok | QMessageBox::Cancel, 
                    QMessageBox::Cancel);
            if (chosenButton != QMessageBox::Ok)
            {
                return; //Save was cancelled
            }
        }
        if (!file.open(QIODevice::WriteOnly))
        {
            QMessageBox::critical(this, tr("Error"), tr("Failed to save file"));
            return; //Aborted
        }
        //All ok - save data
        QString text = ui->plainTextEdit->toPlainText();
        QTextStream out(&file);
        out << text;
        file.close();
    }
}

You should also check whether writing into the file actually succeeded.