Qt中怎样读取文件指定的行?

发布网友 发布时间:2022-04-22 21:02

我来回答

3个回答

热心网友 时间:2023-05-28 20:41

你提到行,很明显你要操作的是文本文件,文本文件是顺序文件,只能用
QFile file("FileName");
QTextStream in(&file);
int i=0;
QString line="";
while (!in.atEnd() && ++i<=lineNo ){
line=in.readLine();
}
其它用途请用随机存储!

热心网友 时间:2023-05-28 20:41

1、qint QFile::readLineData ( char * data, qint maxlen )
[virtual protected]
Reimplemented from QIODevice::readLineData().

2、qint QIODevice::readLine ( char * data, qint 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];
qint lineLength = file.readLine(buf, sizeof(buf));
if (lineLength != -1) {
// the line is available in buf
}
}

3、QByteArray QIODevice::readLine ( qint maxSize = 0 )
This is an overloaded function.
Reads a line from the device, but no more than maxSize characters, and returns the result as a QByteArray.
This function has no way of reporting errors; returning an empty QByteArray() can mean either that no data was currently available for reading, or that an error occurred.

热心网友 时间:2023-05-28 20:42

QFile file(srcDir);
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
int row=0;
while (!file.atEnd())
{
QByteArray line = file.readLine();
if(++row==2){
//QString a=file.readLine();
QString str(line);
qDebug() << str;
}
}
file.close();

}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com