QT学习笔记—文件操作

QIODevice是Qt中所有设备的基接口类,具体IO设备如QFileQTcpSocket等类继承QIODevice提供的抽象接口。

QIODevice是抽象类,不能被实例化。

和C库、Linux下的文件操作等很类似,QIODevice也都提供了open()、read、write()、close()等函数

QIODevice设备打开模式右QIODevice::OpenMode枚举定义

Constant Value Description
QIODevice::NotOpen 0x0000 设备没有打开
QIODevice::ReadOnly 0x0001 只读方式打开,无法写入
QIODevice::WriteOnly 0x0002 只写方式打开,无法读取
QIODevice::ReadWrite ReadOnly WriteOnly
QIODevice::Append 0x0004 附加模式打开,所有数据写到文件尾
QIODevice::Truncate 0x0008 如果可能,设备在被打开之前被截断。设备的所有早期内容都消失
QIODevice::Text 0x0010 读取时,行结束符被转换为’\n’。在编写时,行结束符被转换为本地编码,例如Win32中的’\r\n’
QIODevice::Unbuffered 0x0020 绕过设备的所有缓冲区

QIODevice会区别两种设备: 随机存储设备顺序存储设备

  • 随机存储设备

    支持使用seek()函数定位到任意位置以及使用pos()函数获取位置。QFile、QBuffer属于这样的设备

  • 顺序存储设备

    不支持定位到任意位置,数据必须一次性读取。QTcpSocket、QProcess属于顺序存储设备


文件操作

文件的数据读写一般使用QDataStreamQTextStream来完成

常用方法

  • 判断文件是否存在
bool QFile::exists() const
    
[static] bool QFile::exists(const QString &fileName)
//成功 true
//失败 false
  • 打开文件
//通过文件句柄打开文件
bool QFile::open(FILE *fh, OpenMode mode, FileHandleFlags handleFlags = DontCloseHandle)

//通过文件描述符打开文件
bool QFile::open(int fd, OpenMode mode, FileHandleFlags handleFlags = DontCloseHandle)
   
//继承自其父类QIODevice的打开方法

OpenMode openMode() const

  • 删除文件
bool QFile::remove()
   
//删除名为fileName的文件
[static] bool QFile::remove(const QString &fileName)
  • 重命名文件
bool QFile::rename(const QString &newName)
    
[static] bool QFile::rename(const QString &oldName, const QString &newName)
  • 设置要打开的文件名
void QFile::setFileName(const QString &name)

QFile file;
file.setFileName("readme.txt");
  • 写一个字节
bool putChar(char c)   //继承自父类QIODevice
  • 写一堆数据

    都是继承自父类QIODevice

qint64 write(const char *data, qint64 maxSize)
qint64 write(const char *data)
qint64 write(const QByteArray &byteArray)
  • 读数据

    都是继承自父类QIODevice

qint64 read(char *data, qint64 maxSize)
QByteArray read(qint64 maxSize)

qint64 readLine(char *data, qint64 maxSize)
QByteArray readLine(qint64 maxSize = 0)
    
QByteArray readAll()
  • 关闭文件
void close()
  • 返回发生错误的信息
QString errorString() const
  • 当前读写位置是否在文件尾
bool atEnd() const
  • 获取文件大小
qint64 size() const
  • 获取读写位置(随机存储设备)
qint64 pos() const
  • 定位文件位置
virtual bool seek(qint64 pos)

获取文件信息

相关类: QFileInfo

读写文件

#include "mywidget.h"
#include "ui_mywidget.h"
#include <QFile>
#include <QDebug>
#include <QFileInfo>
#include <QDateTime>

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

    QFile file("readme.txt");
    //打开文件,文件不存在会创建文件
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)){
    
    
        qDebug() << file.errorString();
    }

    qint64 writeSize = file.write("hello! Qt");
    if (writeSize < 0){
    
    
        qDebug() << file.errorString();
    }else{
    
    
        qDebug() << "write bytes :" << writeSize;
    }

    if (file.atEnd()){
    
    
        file.seek(0);    //设置到开头
    }

    writeSize = file.write("Qt Creator,");
    if (writeSize < 0){
    
    
        qDebug() << file.errorString();
    }else{
    
    
        qDebug() << "write bytes :" << writeSize;
    }

    file.close();  //关闭文件

    QFileInfo fileInfo(file); //类似Linux下的函数fstat可以获取文件信息
    qDebug() << "包含文件名的文件绝对路径 :" << fileInfo.absoluteFilePath();
    qDebug() << "不包含文件名的文件绝对路径 :"  << fileInfo.absolutePath();
    qDebug() << "文件基本名称 :" << fileInfo.baseName();
    qDebug() << "文件名 :" << fileInfo.fileName();
    qDebug() << "创建时间 :" << fileInfo.created();
    qDebug() << "文件大小 :" << fileInfo.size();

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
    
    
        qDebug() << file.errorString();
    }

    file.seek(2);

    QByteArray readArray = file.readAll();
    qDebug() << readArray.data();

    if (file.atEnd()){
    
    
        file.seek(0);    //设置到开头
    }

    readArray = file.readAll();
    qDebug() << readArray.data();

    file.close();
}

MyWidget::~MyWidget()
{
    
    
    delete ui;
}

使用文本流读写数据

QTextStream可以操作QIODevice、QByteArray或QString。使用QTextStream重载的流操作符<<>>`,可以方便地读取和写入单词、行和数字。

对文本操作,QTextStream支持字段填充对齐的格式化选项,以及数字的格式化。

#include "mywidget.h"
#include "ui_mywidget.h"
#include <QFile>
#include <QDebug>
#include <QFileInfo>
#include <QDateTime>
#include <QTextStream>

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

    QFile file("readme.txt");

    QTextStream *fileStream = new QTextStream(&file);
    fileStream->setFieldWidth(10);
    //打开文件,文件不存在会创建文件
    if (!file.open(QIODevice::WriteOnly)){
    
    
        qDebug() << file.errorString();
    }

    *fileStream << "Result: "  << qSetFieldWidth(20) << center << 3.14 << 2.7 << "\r\n";
    *fileStream << qSetFieldWidth(10) << left << 10 << 50;
    //qSetFieldWidth(20)设置后面输入数据之间的间隔
    //center:设置为中间对齐方式,left-左对齐,right-右对齐
    file.close();

    if (!file.open(QIODevice::ReadOnly)) {
    
    
        qDebug() << file.errorString();
    }

    QString str;
    QArrayData arr;

    QString strAll;
    QString strLine;

    strLine = fileStream->readLine();  //读取一行
    qDebug() << strLine;
    fileStream->seek(0);    
    strAll = fileStream->readAll();  //读取全部
    qDebug() << strAll;
    fileStream->seek(0);   //定位读位置到开头

    *fileStream >> str;   //读取Result:
    qDebug() << str;
    *fileStream >> str;   //读取3.14
    qDebug() << str;     
    *fileStream >> str;   //读取2.7
    qDebug() << str;   

    file.close();
}

MyWidget::~MyWidget()
{
    
    
    delete ui;
}

数据流QDataStream的使用和文本流QTextStream差不多。

目录操作相关的类:QDir

QDir常用静态函数:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yfLg1bZp-1597658474589)(QT学习笔记—文件操作.assets/image-20200817180026186.png)]

猜你喜欢

转载自blog.csdn.net/qq_36413982/article/details/108061205