Qt 读写文件操作

发布时间 2023-10-18 15:32:12作者: Jeffxue

一、 Qt 中的读文本的内容

1. 以 QTextStream 流的形式来读取文件中的内容。

#include <QFile>
#include <QTextStream>
#include <QDebug>

void ReadData(QString filePath)
{
    QFile file(filePath);

    if(!file.exists())
    {
        qDebug() << "can't find the file";
        return;
    }

    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "can't open the file.";
        return;
    }

    QTextStream stream(&file);
    QString resStr = stream.readAll(); //读取文件中的所有内容

    file.close();
}

2. 向文件中写入数据

void WriteData(QString filePath)
{
    QFile file(filePath);

    if(!file.exists())
    {
        qDebug() << "can't find the file:" << filePath;

    }

    // 当为 QIODevice::ReadWrite 或 QIODevice::ReadOnly 时,如果该目录下不存在对应的文件,就会自动创建该文件,
    // 但是如果没有对应的目录,则不会创建相应的目录和文件,而是直接打开失败。
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append))
    {
        qDebug() << "Open file error";
        return;
    }

    QTextStream stream(&file);
    QString str1 = "only for read test.";
    QString str2 = "中文测试数据\n";

    stream << str1 << str2;

    file.flush();
    file.close();

}