温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Qt中如何使用QFile类打开文件

发布时间:2021-06-11 15:23:53 来源:亿速云 阅读:1864 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关Qt中如何使用QFile类打开文件的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

Qt文件操作类QFile简介

Qt中使用QFile类来操作文件的输入/输出。继承至QIODevice,QIODevice类是输入/输出设备的基类,

为设备提供了公共实现和抽象接口用于读写块数据。QIODevice又继承至QObject。

1、使用QFile类打开文件

QFile的构造函数

QFile(const QString &name) //传入一个文件路径

构造完成后,并没有打开文件,需要使用QFile::open函数来打开文件

[virtual] bool QFile::open(OpenMode mode);
/*
*OpenMode mode 打开方式,是一个枚举类型
*QIODevice::NotOpen 不打开
*QIODevice::ReadOnly 只读方式
*QIODevice::WriteOnly 读写方式
*QIODevice::ReadWrite 读写方式
*QIODevice::Append   追加方式
*QIODevice::Truncate 阶段方式
*QIODevice::Text     转换不同平台的换行,读的时候把所有换行转成'\n',写的时候再把'\n'转换对应平台的换行
*QIODevice::Unbuffered 不使用缓冲区
*/

例如:

QFile file("d:/123.txt");
file.open(QIODevice::ReadOnly);

2、QFile类关闭文件

[virtual] void QFileDevice::close(); //刷新缓冲区,并关闭文件

3、QFile类文件读操作

QIODevice::read函数

QByteArray QIODevice::read(qint64 maxSize);//读取maxSize个字节,内部位置指针后移maxSize,并返回一个QByteArray对象。

例如:

QFile file("d:/123.txt");
file.open(QIODevice::ReadOnly);
qDebug() << file.read(10) << endl;
file.close();

QIODevice::readLine函数

QByteArray QIODevice::readLine(qint64 maxSize = 0) //读取一行,但是这一行不能超过maxSize字节,maxSize = 0代表不限制行字节数。

例如:

QFile file("d:/123.txt");
file.open(QIODevice::ReadOnly);
qDebug() << file.readLine(10) << endl; 
file.close();

QIODevice::readAll函数

QByteArray QIODevice::readAll()

4、QFile类文件写操作

QIODevice::write函数

qint64 QIODevice::write(const QByteArray &byteArray); //将byteArray写入文件,写完内部位置指针后移

例如:

QFile file("d:/123.txt");
file.open(QIODevice::ReadWrite | QIODevice::Text); //打开模式可以使用‘|'组合
QByteArray byte("hellworld");
file.write(byte);
file.write(byte);
file.close();

5、QDataStream

流控文件输入输出可以使用QDataStream。

流控写入

#include <QDataStream>
#include <QDebug>
#include <QFile>
int main(int argc, char**argv)
{
    QFile file("d:/123.txt");
    file.open(QIODevice::ReadWrite);
    QDataStream stream(&file);
    int a = 10;
    QString str = "helloworld";
    stream << a << str;
    file.close();
    return 0;
}

流控读取

#include <QDataStream>
#include <QDebug>
#include <QFile>
int main(int argc, char**argv)
{
    QFile file("d:/123.txt");
    file.open(QIODevice::ReadWrite);

    QDataStream stream(&file);
    int a;
    QString str;
    stream >> a >> str;
    qDebug() << "a:" << a << "str:" << str << endl;
    file.close();
    return 0;
}

感谢各位的阅读!关于“Qt中如何使用QFile类打开文件”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI