Qt实现在项目同级文件夹新建保存数据的文件夹,通过按钮新建文件

发布时间 2023-09-23 12:56:56作者: liutao_111

新建文件夹

需要的头文件

#include <QFile>
#include <QTextStream>
#include <QDir>

通过一个函数来判断是否存在指定的文件夹,如果存在则跳过,否则创建文件夹。

bool Widget::isExists()
{
    QString folderName = "dataFolder"; // 文件夹名称
    QString path = QDir::currentPath() + "/.." + "/" + folderName; // 文件夹路径
    QDir dir;
    if (dir.exists(path)) {
        qDebug() << "Folder already exists:" << folderName;
        return true;
    } else {
        if (dir.mkdir(path)) {
            qDebug() << "Folder created successfully:" << folderName;
            return true;
        } else {
            qWarning() << "Failed to create folder:" << folderName;
        }
    }
    return false;
}

通过按钮来点击生成txt文件,保存在刚刚生成的文件夹下

void Widget::on_pushButton_clicked()
{
    if(isExists()){
        static int fileCount = 0; // 记录文件计数器
        QString fileName = QString("../dataFolder/example%1.txt").arg(fileCount); // 设置文件名
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream stream(&file);
            for(int i = 0; i < 1200; i++){
                stream << "This is example " << fileCount << "."; // 写入数据
            }
            file.close();
            qDebug() << "File created and data written successfully:" << fileName;
            fileCount++; // 计数器加一,为下一个文件准备名称
        } else {
            qWarning() << "Failed to create or open the file:" << fileName;
        }
    }
}