如何在不存入QString的情况下跳过QFile的N行内容?
Great question! When working with Qt's QFile, you don't have to read and discard those first 999 lines explicitly—instead, you can use QTextStream to skip them efficiently, just like how istream::ignore works for standard streams.
Here's how you can implement this:
#include <QFile> #include <QTextStream> int main() { QFile file("file.txt"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { // Handle error: file couldn't be opened return 1; } QTextStream stream(&file); // Skip the first 999 lines for (unsigned int i = 0; i < 999; ++i) { // Read until the newline character (and discard the result) stream.readUntil('\n'); } // Now read the 1000th line QString thousandthLine = stream.readLine(); // Do whatever you need with thousandthLine... file.close(); return 0; }
Key details to note:
QTextStream::readUntil('\n')does exactly what you need: it reads all characters from the current position up to (and including) the newline character, but since we don't store the returnedQString, those lines are effectively skipped without unnecessary copies to your own variables.- Unlike using raw
QFile::seek(), this approach handles cross-platform newline formats (\n,\r\n) automatically, so you don't have to worry about miscalculating byte offsets for different line endings. - Always remember to check if the file opened successfully—Qt won't throw exceptions for file access errors by default, so explicit error handling is a good practice.
If you need to handle cases where there might be leading whitespace before lines, you can add stream.skipWhiteSpace(); inside the loop before readUntil('\n'), but that's optional depending on your use case.
内容的提问来源于stack exchange,提问作者Pippin
相关产品推荐
相关产品推荐

