简体   繁体   English

如何在Qt中保存QTextStream?

[英]How to save QTextStream in Qt?

I have to read a text file in Qt line by line. 我必须逐行读取Qt中的文本文件。

So I made a function that reads first X lines of the file. 因此,我做了一个读取文件前X行的函数。 But when the function is called next time I want the reading to start from line X + 1 . 但是,当下次调用该函数时, 我希望读数从X + 1行开始 I know that I can do this just by skipping the first X lines. 我知道我可以跳过前X行来做到这一点。

But I tried to save the QTextStream object which gives me the error: 但是我试图保存QTextStream对象,这给了我错误:

in expansion of macro Q_DISABLE_COPY . 在扩展Q_DISABLE_COPY

and if I save the pointer to QTextStream object, then my application hangs. 如果我保存了指向QTextStream对象的指针,则我的应用程序将挂起。 Does this mean that skipping first X lines is the only way to do this? 这是否意味着跳过前X行是唯一的方法?

You can save the stream's current position using pos() and then seek(position) to resume from the previous reached point. 您可以使用pos()保存流的当前位置,然后使用seek(position)从上一个到达的点恢复。

I suspect your QTextStream is created on the stack each time you read, which is why if you try using a pointer to it the next time it crashes, because it is a dangling pointer pointing to a no longer valid object. 我怀疑您的QTextStream每次读取时都会在堆栈上创建,这就是为什么如果您下次尝试使用指向它的指针时会崩溃的原因,因为它是指向不再有效对象的悬空指针。

So you either need to make the text stream persistent, so either implement it is a member variable or allocate it on the heap with new which will work with a pointer, or simply create a new text stream and seek to the previous position. 所以,你要么需要使文本流持续性,所以无论是实现它是一个成员变量或分配它与堆new将与指针工作,或者干脆创建一个新的文本流,并寻求到以前的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM