我是靠谱客的博主 不安秋天,这篇文章主要介绍Qt基础开发之Qt文件操作类QFile读写文件的详细方法与实例及QDataStream的使用方法,现在分享给大家,希望可以做个参考。

Qt文件操作类QFile简介

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

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

1、使用QFile类打开文件

QFile的构造函数

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
[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 不使用缓冲区 */

例如:

复制代码
1
2
QFile file("d:/123.txt"); file.open(QIODevice::ReadOnly);

2、QFile类关闭文件

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

3、QFile类文件读操作

QIODevice::read函数

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

例如:

复制代码
1
2
3
4
QFile file("d:/123.txt"); file.open(QIODevice::ReadOnly); qDebug() << file.read(10) << endl; file.close();

QIODevice::readLine函数

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

例如:

复制代码
1
2
3
4
QFile file("d:/123.txt"); file.open(QIODevice::ReadOnly); qDebug() << file.readLine(10) << endl; file.close();

QIODevice::readAll函数

复制代码
1
QByteArray QIODevice::readAll()

4、QFile类文件写操作

QIODevice::write函数

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

例如:

复制代码
1
2
3
4
5
6
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。

流控写入

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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; }

流控读取

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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读写文件的详细方法与实例及QDataStream的使用方法,更多关于Qt基础开发知识请查看下面的相关链接

最后

以上就是不安秋天最近收集整理的关于Qt基础开发之Qt文件操作类QFile读写文件的详细方法与实例及QDataStream的使用方法的全部内容,更多相关Qt基础开发之Qt文件操作类QFile读写文件内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(360)

评论列表共有 0 条评论

立即
投稿
返回
顶部