前言:
读写文本文件有两种方法:
1、直接利用传统的QFile类方法。
2、利用QTextStream类方法。
下面讲一讲使用QFile类提供的方法来读文件。
实例:
1、首先建立控制台应用程序,类名为“QFile”。
2、在源文件“main.cpp”的具体实现中添加如下代码:
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、此函数用于指定文件的打开方式。
有如下打开方式: