简体   繁体   English

通过QTextStream反复向QBuffer读写

[英]Repeatedly write and read to/from QBuffer via QTextStream

I am trying to repeatedly write and read to/from a QBuffer object via QTextStream . 我试图通过QTextStream反复向/从QBuffer对象写入和读取。 First I construct both objects: 首先,我构造了两个对象:

QBuffer b;
b.open(QIODevice::ReadWrite);
QTextStream s(&b);
// Setup text stream here

Then I write three different portions of information and read them back: 然后,我编写了三个不同的信息部分,并将它们读回去:

s << "Test" << 666 << endl << flush;
s.seek(0);
qDebug() << s.readAll();

s << "X" << endl << flush;
s.seek(0);
qDebug() << s.readAll();

s << "Test" << 777 << endl << flush;
s.seek(0);
qDebug() << s.readAll();

Of course I do not get the data portion I wrote immediately before, but the cumulated data: 当然,我不会得到我之前写的数据部分,而是累积的数据:

"Test666\n"
"Test666\nX\n"
"Test666\nX\nTest777\n"

I could do adaptive seek calls to get the correct data but I do not want the QBuffer to grow infinitely . 我可以进行自适应寻求调用以获取正确的数据,但我希望QBuffer 无限增长

I tried a s.reset() call between writes but the result is the same. 我尝试在s.reset()写入之间进行s.reset()调用,但结果相同。 Calling reset() or open()/close() directly on the buffer gives a crippled result (which is expected since the stream is bypassed): 直接在缓冲区上调用reset()open()/close()会产生严重的结果(这是预期的,因为绕过了流):

"Test666\n"
"X\nst666\n"
"Test777\n"

I could probably build a new buffer for every cycle, open it and attach it to the stream but that is slow. 我可能可以为每个周期建立一个新的缓冲区,将其打开并将其附加到流中,但这很慢。

Is there a proper and fast solution for this use case? 是否有针对该用例的适当且快速的解决方案?

You can access QBuffer 's internal QByteArray storage directly with QBuffer::buffer() and then delete everything with QByteArray::clear() . 您可以直接使用QBuffer::buffer()访问QBuffer的内部QByteArray存储,然后使用QByteArray::clear()删除所有内容。 Then manually seek() back to the start. 然后手动将seek()重新开始。

    QBuffer b;
    b.open(QIODevice::ReadWrite);
    QTextStream s(&b);

    s << "Test" << 666 << endl << flush;
    s.seek(0);
    qDebug() << s.readAll();

    b.buffer().clear();
    s.seek(0);

    s << "X" << endl << flush;
    s.seek(0);
    qDebug() << s.readAll();

    b.buffer().clear();
    s.seek(0);

    s << "Test" << 777 << endl << flush;
    s.seek(0);
    qDebug() << s.readAll();
"Test666\n"
"X\n"
"Test777\n"

QTextStream also has a constructor which takes a QByteArray directly and creates the QBuffer automatically, which may save a little code in this case. QTextStream还具有一个构造函数 ,该构造函数直接使用QByteArray并自动创建QBuffer ,在这种情况下,可以节省一些代码。

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

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