0. Preface
Sometimes, depending on the requirement, you need to read the last line of the text.
If it is a small text, read it in order and then take the last line and then Ok; but if it is a large text, even if it is placed in a thread, there will be a delay in reading the last line, which is relatively time-consuming.
1. Solution
CheckQFile
Help manual, which has
bool seek(qint64 pos);
It means finding the location in the device. Returns true when successful; otherwise returns false.
Therefore, you can check from the back to the previous position. If you include a newline, it means that the last line has been obtained.
The code is as follows:
QFile file("C:\\Users\\Desktop\\"); if((QIODevice::ReadOnly | QIODevice::Text)) { QTextStream in(&file); (QTextCodec::codecForName("UTF-8")); int nSize = (); // When size == 0, return if(nSize < 1) { qDebug().noquote() << "No data."; return; } // When size == 1, jump out int nTmp = 0; while(!()){ (); ++nTmp; if(nTmp > 1) { break; } } // Get 1 line of content if(nTmp < 2) { (0); // Move the cursor to the text start position qDebug().noquote() << "Read the first line: " << (); return; } // When size > 1, read from behind to front. When reading "\r\n", add the length of "\r\n", so that the position is adjusted to the last line and read a single line // Different systems may have different lines splitting, and the Windows platform is "\r\n" int nIndex = 1; (nSize - nIndex); while(!().contains("\r\n")) { ++nIndex; (nSize - nIndex); } (nSize - nIndex + 2); // Move the cursor to the last line to start qDebug().noquote() << "Read the last line: " << (); }
It is divided into three situations:
- When the text is empty, prompt or return
- When there is only one line of text, the first line is output
- When text > one line, perform an operation
2. Results
May you have a month of overjoyment.
Supplement: The problem of endless empty lines at the end of qt file
QString line; QTextStream in(&file1); //Construct streams with files while(1) { line=();//Loop reading the lower line if(!())//There is content of the string, and the newline character is also content { (line); } else break; }
This will cause the last line of the file to be a blank line and cannot be read because it is an empty string (and there is no newline afterwards), and cannot be read. If it is an empty line in the middle of the file, although it is also an empty string, there is a newline at the end of this line (it is not an empty string). It can be continued to read, which is caused by this reason.
Solution:
QTextStream in(&file1); //Construct streams with files lis = ().split("\n");
Summarize
This is the end of this article about Qt's solution to quickly read the last line of content of a large file. For more related Qt's content of the last line of content of a large file, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!