Qt: QFile类读写文本实例

前言:

读写文本文件有两种方法:

1、直接利用传统的QFile类方法。

2、利用QTextStream类方法。


下面讲一讲使用QFile类提供的方法来读文件。

实例:

1、首先建立控制台应用程序,类名为“QFile”。
2、在源文件“main.cpp”的具体实现中添加如下代码:

<span style="font-size:14px;">#include <QCoreApplication>
#include <QFile>
#include <QtDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QFile file("textFile1.txt");    //构造一个QFile对象
    if(file.open(QIODevice::ReadOnly))  //以只读方式打开
    {
        char buffer[8]; //缓冲区设置为8个字节
        qint64 lineLen = file.readLine(buffer , sizeof(buffer));    //以行为单位进行读取
        if(lineLen != -1)
        {
            qDebug()<<buffer;   //将缓冲区中的内容输出到控制台
        }
    }
    file.close();   //关闭文件
    return a.exec();
}
</span>

3、新建“.txt”文件

在当前源文件的目录下新建一个txt文件,文件名为“textFile1.txt”。并在文件“textFile1.txt“中输入内容。(此处我输入的是”12345678“)。

4、运行程序,结果如下:



问题:

细心的朋友可能会发现,在程序中我是设定的8个字节,可是为什么只读出了7个字符呢?

这时就需要讲一讲readLine()函数的用法了。

英文原版如下:

qint64 QIODevice::readLine(char * data, qint64 maxSize)
This function reads a line of ASCII characters from the device, up to a maximum of maxSize - 1 bytes, stores the characters in data, and returns the number of bytes read. 

If a line could not be read but no error ocurred, this function returns 0. If an error occurs, this function returns the length of what could be read, or -1 if nothing was read.

A terminating '\0' byte is always appended to data, so maxSize must be larger than 1.

Data is read until either of the following conditions are met:

The first '\n' character is read.
maxSize - 1 bytes are read.
The end of the device data is detected.
For example, the following code reads a line of characters from a file:

QFile file("box.txt");
if (file.open(QFile::ReadOnly)) {
    char buf[1024];
    qint64 lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        // the line is available in buf
    }
}
The newline character ('\n') is included in the buffer. If a newline is not encountered before maxSize - 1 bytes are read, a newline will not be inserted into the buffer. 

On windows newline characters are replaced with '\n'.

函数解析:
qint64 QIODevice::readLine(char * data, qint64 maxSize)

1、如果读取正确,函数的返回值则为读取的字节数;如果读取错误,函数的返回值则为-1。

2、字符串以“\0”结束,所以读取的字节长度必须大于或者等于2。


如果我们将程序中的语句:  char buffer[8];改为  char buffer[1]; 编译器输出的提示如下:




bool QIODevice::open(OpenMode mode)

1、此函数用于指定文件的打开方式。

有如下打开方式:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值