Qt 读写文件操作

一、 Qt 中的读文本的内容

  • QTextStream 流读取文件中的内容,如读取每行的内容会自动去除行尾的换行符 \n,而 QByteArray会保存所有的字符,不会去除末尾的换行符。

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

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

/// <summary>
/// 一次读取文件中的所有内容。
/// </summary>
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();
}


/// <summary>
/// 逐行读取所有内容
/// </summary>
void ReadData_M2(QString filePath)
{
    QFile file(filePath);

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "file open failed" << endl;
        return;
    }

    QTextStream stream(&file);

    while(!stream.atEnd())
    {
        QString line = file.readLine();
        qDebug() << line << endl;
    }

    qDebug() << "Read all lines" << endl;
}

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();

}
posted @ 2023-10-18 15:29  Jeffxue  阅读(273)  评论(0编辑  收藏  举报