使用Qt的QDir/QFile类创建文件夹、以时间命名的dat/txt等文件、从文件中读写数据等操作

9 篇文章 12 订阅

结尾附赠源码

一、创建文件夹

使用QDir类用来创建文件夹,可以是绝对路径、也可以是相对路径。

例如:绝对路径

  QDir("/home/user/Documents")
  QDir("C:/Documents and Settings")

例如:相对路径

QDir("images/landscape.png")

主要操作如下:

// 声明目录对象
QDir dir(path);
// 判断此目录文件是否存在
if (dir.exists(path)) {
        return path;
}

二、创建文件

使用QFire类来创建文件。

exists();用来判断文件是否存在。
QFile::WriteOnly|QFile::Text;以只写文本方式创建文件

三、创建文件夹和文件的函数实现

1. 新建项目

2. 在项目的头文件(.h)中加入函数声明,如下

QString   createMultipleFolders(const QString path);             // 创建文件夹
QString   createFile(const QString path,const QString suffix);   // 创建.dat文件

3. 在(.cpp)文件中添加以下代码

// 1. 引入头文件
#include <QDateTime>
#include <QFile>
#include <QDir>

// 2. 在构造函数中添加代码
QString path = createMultipleFolders("D:\\1\\001");
QString pathFile = createFile(path,".txt");

// 3.  创建多级文件夹 
QString Widget::createMultipleFolders(const QString path)
{
    QDir dir(path);
    if (dir.exists(path)) {
        return path;
    }

    QString parentDir = createMultipleFolders(path.mid(0, path.lastIndexOf('\\')));//截取根目录
    QString dirName = path.mid(path.lastIndexOf('\\') + 1);//截取父目录
    
QDir parentPath(parentDir);
    if (!dirName.isEmpty())
    {
        parentPath.mkpath(dirName);
    }

    return parentDir + "\\" + dirName;
}

// 4. 创建文件 
QString Widget::createFile(const QString path,const QString suffix)
{
    QString createTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH-mm-ss");//文件名不能用“:”命名
    QString fileName = path + "\\" + createTime + suffix;
    QFile file(fileName);

    if(file.exists())
    {
        return fileName;
    }
    else
    {
        // 如果没有此文件,就创建
        file.open(QFile::WriteOnly|QFile::Text|QIODevice::Append);
    }

    return fileName;
}

4. 实现效果

创建成功! 不局限与".dat”文件,其他后缀名的也可以,自己试一下吧!

四、将数据写入文件

1. 使用QFire类;

2. QFile::WriteOnly|QFile::Text|QIODevice::Append;以只写文本方式创建文件,以追加方式写入文件;

3. 调用write()函数将数据写入指定文件中。

4. 实现如下

QFile file(pathFile);//上面操作已经创建出来的文件名
file.open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Text);
file.write("你好!");

5. 运行后,打开文件,可以看到你写入的数据

五、从文件中读取数据

1. 使用QFire类;

2. QFile::ReadWrite|QFile::Text;以读写方式打开文件;

3. 调用atEnd()函数判断是否读取到最后;

4. 调用readLine();函数一行一行读取数据

5. 读取完后,需要关闭文件。

6. 实现如下

在头文件中添加函数声明

void  readFileData();                            // 从文件中读取数据

在.cpp文件中实现

/* 从指定文件中读取数据 */
void Widget::readFileData()
{
    QFile file1("D:/1/001/2022-05-28 11-17-09.txt");
    // 读写模式打开文件
    file1.open(QIODevice::ReadWrite | QIODevice::Text);
    QString data;
    QStringList user_data;

    //判断文件是否打开成功
    if(file1.isOpen())
    {
        if(file1.size() != 0)//文件有数据
        {
//            qDebug() << "文件有数据";

            //一行一行一直读,直至读取失败
            while(!file1.atEnd())
            {
                // readAll();全部取出来
                data=file1.readLine();//读取一行存到data里
//                user_data=data.split(" ");//将data里的数据以空格作为分隔符存到user_data
                //......
                // 处理数据
                qDebug() << data; // 输出结果为:"你好!"
            }
            // 读取完后关闭文件
            file1.close();
        }
    }
    else
    {
        qDebug() << "文件打开失败";
    }
}

7. 运行后,能够获取到数据

 至此所有跟文件有关的操作就结束啦。下面附赠源码,可以直接复制可运行。

.pro 文件源码

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    widget.cpp

HEADERS += \
    widget.h

FORMS += \
    widget.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

.h 头文件源码

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    QString   createMultipleFolders(const QString path);             // 创建文件夹
    QString   createFile(const QString path,const QString suffix);   // 创建.dat文件
    void      readFileData();                            // 从文件中读取数据

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

main.cpp源码

#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

.cpp源码

#include "widget.h"
#include "ui_widget.h"

#include <QDateTime>
#include <QFile>
#include <QDir>
#include <QDebug>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 创建文件夹和文件
    QString path = createMultipleFolders("D:\\1\\001");
    QString pathFile = createFile(path,".txt");

    // 将数据写入文件中
    QFile file(pathFile);//上面操作已经创建出来的文件名
    file.open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Text);
    file.write("你好!");

    // 文件中读取数据
    readFileData();

}

Widget::~Widget()
{
    delete ui;
}
/* 创建多级文件夹 */
QString Widget::createMultipleFolders(const QString path)
{
    QDir dir(path);
    if (dir.exists(path)) {
        return path;
    }

    QString parentDir = createMultipleFolders(path.mid(0, path.lastIndexOf('\\')));//截取根目录
    QString dirName = path.mid(path.lastIndexOf('\\') + 1);//截取父目录
    QDir parentPath(parentDir);
    if (!dirName.isEmpty())
    {
        parentPath.mkpath(dirName);
    }

    return parentDir + "\\" + dirName;
}

/* 创建文件 */
QString Widget::createFile(const QString path,const QString suffix)
{
    QString createTime = QDateTime::currentDateTime().toString("yyyy-MM-dd HH-mm-ss");//文件名不能用“:”命名
    QString fileName = path + "\\" + createTime + suffix;
    QFile file(fileName);

    if(file.exists())
    {
        return fileName;
    }
    else
    {
        // 如果没有此文件,就创建
        file.open(QFile::WriteOnly|QFile::Text|QIODevice::Append);
    }

    return fileName;
}

/* 从指定文件中读取数据 */
void Widget::readFileData()
{
    QFile file1("D:/1/001/2022-05-28 11-17-09.txt");
    // 读写模式打开文件
    file1.open(QIODevice::ReadWrite | QIODevice::Text);
    QString data;
    QStringList user_data;

    //判断文件是否打开成功
    if(file1.isOpen())
    {
        if(file1.size() != 0)//文件有数据
        {
//            qDebug() << "文件有数据";

            //一行一行一直读,直至读取失败
            while(!file1.atEnd())
            {
                // readAll();全部取出来
                data=file1.readLine();//读取一行存到data里
//                user_data=data.split(" ");//将data里的数据以空格作为分隔符存到user_data
                //......
                // 处理数据
                qDebug() << data; // 输出结果为:"你好!"
            }
            // 读取完后关闭文件
            file1.close();
        }
    }
    else
    {
        qDebug() << "文件打开失败";
    }
}


希望大家可以自己多试试。

  • 19
    点赞
  • 115
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值