要实现按照年月日时分秒文件名创建文件并保存到按照年月日生成的文件夹中,可以使用以下代码示例:
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QFile>
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
// 获取当前日期和时间
QDateTime currentDateTime = QDateTime::currentDateTime();
// 创建存储目录
QString directoryName = currentDateTime.toString("yyyy-MM-dd");
QDir directory;
if (!directory.exists(directoryName))
directory.mkpath(directoryName);
// 创建文件名
QString fileName = currentDateTime.toString("yyyy-MM-dd-hh-mm-ss") + ".txt";
// 创建文件并保存内容
QFile file(directoryName + "/" + fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream stream(&file);
stream << "Hello, World!";
file.close();
qDebug() << "File saved successfully.";
}
else
{
qDebug() << "Failed to save file.";
return -1;
}
return 0;
}
在这个示例中,我们首先获取当前的日期和时间,并使用toString()
函数将其格式化为”yyyy-MM-dd”形式,用作存储目录的名称。然后,我们使用QDir
类来创建该目录(如果不存在)。
接下来,我们再次使用toString()
函数将当前日期和时间格式化为”yyyy-MM-dd-hh-mm-ss.txt”形式,并用作要创建的文件名。
然后,我们通过创建一个QFile
对象,并打开它以进行写入操作。我们使用QTextStream
来向文件中写入文本内容(在示例中是”Hello, World!“),然后关闭文件。
这样,就会在按照年月日命名的目录下创建一个以当前时分秒命名的文件,并将内容保存到该文件中。如果操作成功,将会打印出”File saved successfully.“消息,否则会打印出”Failed to save file.“消息。
内容由零声教学AI助手提供,问题来源于学员提问