Qt 创建文件 用QFile和QDir类

项目需求是 根据日期创建多级子文件夹, 根目录保存 log.txt

控制台程序实现

如下执行结果

createFile 为程序目录

文档结构:



源码:

#include <QtCore/QCoreApplication>
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QObject>
 
 
void createFile(QString filePath,QString fileName)
{
    QDir tempDir;
    //临时保存程序当前路径
    QString currentDir = tempDir.currentPath();
    //如果filePath路径不存在,创建它
    if(!tempDir.exists(filePath))
    {
        qDebug()<<QObject::tr("不存在该路径")<<endl;
        tempDir.mkpath(filePath);
    }
    QFile *tempFile = new QFile;
    //将程序的执行路径设置到filePath下
    tempDir.setCurrent(filePath);
    qDebug()<<tempDir.currentPath();
    //检查filePath路径下是否存在文件fileName,如果停止操作。
    if(tempFile->exists(fileName))
    {
        qDebug()<<QObject::tr("文件存在");
        return ;
    }
    //此时,路径下没有fileName文件,使用下面代码在当前路径下创建文件
    tempFile->setFileName(fileName);
    if(!tempFile->open(QIODevice::WriteOnly|QIODevice::Text))
    {
        qDebug()<<QObject::tr("打开失败");
    }
    tempFile->close();
    //将程序当前路径设置为原来的路径
    tempDir.setCurrent(currentDir);
    qDebug()<<tempDir.currentPath();
}
 
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
    // 获取当前日期
    QDateTime current_date_time =QDateTime::currentDateTime();
    QString current_date =current_date_time.toString("yyyy/MM/dd");
 
 
    QString fileDir = "./Log/" + current_date;
 
 
    createFile(fileDir, "log.txt");
 
 
    return a.exec();
}
 
 

猜你喜欢

转载自blog.csdn.net/Empty_Android/article/details/80655355
今日推荐