Qt 创建文件 用QFile和QDir类

本文介绍了一个简单的C++程序,用于根据当前日期动态创建多级子文件夹,并在指定路径下生成log.txt文件。程序首先获取当前日期,然后通过QDir和QFile等Qt类库创建相应目录及文件。

项目需求是 根据日期创建多级子文件夹, 根目录保存 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();
}


 

在CMake项目中配置对`QString`、`QFile``QDir`的支持,需要确保Qt的核心模块(`QtCore`)被正确引入。这些均属于Qt Core模块,因此必须在`CMakeLists.txt`中声明对`Core`组件的依赖。 ### 配置Qt模块支持 使用`find_package`命令查找已安装的Qt5或Qt6库,并指定所需的组件。对于`QString`、`QFile``QDir`的支持,应包含`Core`模块: ```cmake cmake_minimum_required(VERSION 3.14) project(MyQtApp) # 查找Qt库 find_package(Qt5 COMPONENTS Core REQUIRED) # 或者对于Qt6 # find_package(Qt6 COMPONENTS Core REQUIRED) # 添加可执行文件 add_executable(myapp main.cpp) # 链接Qt Core库 target_link_libraries(myapp PRIVATE Qt5::Core) # 对于Qt6则为: # target_link_libraries(myapp PRIVATE Qt6::Core) ``` 该配置使得编译器能够识别并处理包含`QString`、`QFile`、`QDir`等核心的代码,并正确链接到Qt Core库中的实现[^1]。 ### 包含头文件与使用示例 在C++源码中,可以正常包含相关头文件并使用这些: ```cpp #include <QString> #include <QFile> #include <QDir> #include <QDebug> int main() { QString path = QDir::homePath() + "/example.txt"; QFile file(path); if (file.open(QIODevice::WriteOnly)) { QTextStream out(&file); out << "Hello, Qt World!"; file.close(); } else { qDebug() << "Failed to open file for writing."; } return 0; } ``` 此代码片段展示了如何结合`QString`、`QFile``QDir`创建一个文件路径并写入文本内容,体现了这些在实际应用中的基本用法[^2]。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值