Qt深入浅出(十)文件读写

素颜马尾好姑娘i 2023-07-16 03:55 36阅读 0赞

文件读写

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

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

1 使用QFile打开文件

  • QFile的构造函数

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

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

    [ virtual] bool QFile::open( OpenMode mode);

    1. /*
    2. *OpenMode mode 打开方式,是一个枚举类型
    3. *QIODevice::NotOpen 不打开
    4. *QIODevice::ReadOnly 只读方式
    5. *QIODevice::WriteOnly 读写方式
    6. *QIODevice::ReadWrite 读写方式
    7. *QIODevice::Append 追加方式
    8. *QIODevice::Truncate 阶段方式
    9. *QIODevice::Text 转换不同平台的换行,读的时候把所有换行转成'\n',写的时候再把'\n'转换对应平台的换行
    10. *QIODevice::Unbuffered 不使用缓冲区
    11. */

例如:

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

2 关闭文件

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

3 文件读操作

  • QIODevice::read函数

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

例如:

  1. QFile file ( "d:/123.txt" );
  2. file. open( QIODevice::ReadOnly);
  3. qDebug() << file. read( 10) << endl;
  4. file. close();
  • QIODevice::readLine函数

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

例如:

  1. QFile file ( "d:/123.txt" );
  2. file. open( QIODevice::ReadOnly);
  3. qDebug() << file. readLine( 10) << endl;
  4. file. close();
  • QIODevice::readAll函数

    QByteArray QIODevice::readAll()

4 文件写操作

  • QIODevice::write函数

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

例如:

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

5 使用QDataStream

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

  • 流控写入

    include

    1. #include <QDebug>
    2. #include <QFile>
    3. int main ( int argc , char** argv )
    4. {
    5. QFile file ( "d:/123.txt" );
    6. file. open( QIODevice::ReadWrite);
    7. QDataStream stream ( & file );
    8. int a = 10;
    9. QString str = "helloworld";
    10. stream << a << str;
    11. file. close();
    12. return 0;
    13. }
  • 流控读取

    include

    1. #include <QDebug>
    2. #include <QFile>
    3. int main ( int argc , char** argv )
    4. {
    5. QFile file ( "d:/123.txt" );
    6. file. open( QIODevice::ReadWrite);
    7. QDataStream stream ( & file );
    8. int a;
    9. QString str;
    10. stream >> a >> str;
    11. qDebug() << "a:" << a << "str:" << str << endl;
    12. file. close();
    13. return 0;
    14. }

发表评论

表情:
评论列表 (有 0 条评论,36人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Qt DOMXML文件

    QXmlStreamReader:一种快速的基于流的方式访问良格式 XML 文档,特别适合于实现一次解析器(所谓“一次解析器”,可以理解成我们只需读取文档一次,然后像一个遍历器

    相关 QT 文件

    上一章我们介绍了有关二进制文件的读写。二进制文件比较小巧,却不是人可读的格式。而文本文件是一种人可读的文件。为了操作这种文件,我们需要使用`QTextS