导出文件的示例工具类
首先提供一个工具类,用于将指定范围的数字写入txt文件。
#ifndef UTILITIES_H #define UTILITIES_H #include <QString> #include <QFile> #include <QTextStream> #include <QDateTime> #include <QDir> #include <QDebug> class Utilities { public: static bool writeNumbersToFile(int start, int end, const QString& prefix = "numbers") { if (start > end) { qDebug() << "起始数字不能大于结束数字"; return false; } // 获取当前时间并格式化为文件名 QDateTime currentTime = QDateTime::currentDateTime(); QString timeString = currentTime.toString("yyyy-MM-dd_hh-mm-ss"); QString fileName = QString("%1_%2_to_%3_%4.txt") .arg(prefix) .arg(start) .arg(end) .arg(timeString); // 创建文件对象 QFile file(fileName); // 以写入模式打开文件 if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug() << "无法创建文件:" << fileName; return false; } // 创建文本流 QTextStream out(&file); // 写入指定范围的数字 int count = 0; for (int i = start; i <= end; ++i) { out << i; count++; // 每10个数字换行 if (count % 10 == 0 || i == end) { out << "\n"; } else { out << " "; // 数字之间用空格分隔 } } // 关闭文件 file.close(); qDebug() << "成功写入文件:" << fileName; qDebug() << "文件路径:" << QDir::currentPath() + "/" + fileName; qDebug() << "写入数字范围:" << start << "到" << end << ",共" << (end - start + 1) << "个数字"; return true; } // 获取当前工作目录 static QString getCurrentPath() { return QDir::currentPath(); } // 检查文件是否存在 static bool fileExists(const QString& fileName) { QFile file(fileName); return file.exists(); } }; #endif // UTILITIES_H