使用QFileInfo类判断同名文件存在

问题描述:使用QT保存文件时,如果文件名相同,保存后原来的文件会被覆盖
引用博客

首先在QT项目中新建一个按钮

再右击选择转到槽,这时候就会跳转到刚刚生成的槽函数

代码

void MainWindow::on_pushButton_5_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save file"), QDir::currentPath(), tr("Text files (*.txt)"));
    if (!fileName.isEmpty()) {
        qDebug() << "Selected file:" << fileName;
        // 检查文件是否存在
        QFileInfo fileInfo(fileName);
        if (fileInfo.exists()) {
            QMessageBox msgBox;
            msgBox.setText(tr("The selected file already exists."));
            msgBox.setInformativeText(tr("Do you want to overwrite it?"));
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel);
            int ret = msgBox.exec();
            switch (ret) {
                case QMessageBox::Yes:
                    // 用户选择覆盖现有文件,继续执行保存操作
                    break;
                case QMessageBox::No:
                    // 用户选择另存为,重新弹出保存对话框
                    on_pushButton_5_clicked();
                    return;
                case QMessageBox::Cancel:
                    // 用户取消操作,退出函数
                    return;
                default:
                    return;
            }
        }
        // 在这里进行自己的操作,例如将数据写入文本文件中
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << "Hello World!";
            file.close();
        }
    }
}

记住根据自己的需求把case QMessageBox::No:下面的槽函数换成相应的。

效果

猜你喜欢

转载自blog.csdn.net/m0_51650696/article/details/142816510