新建文件夹
需要的头文件
#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;
}
}
}
标签:Qt,新建,文件夹,QString,file,按钮,include
From: https://www.cnblogs.com/LeoTao-777/p/17724239.html