初始stringbuf(streambuf)容量

时间:2019-05-16 16:29:54

标签: c++ capacity stringbuf

我正在尝试从抽象源(下面的receive方法接收字节流,并将这些字节添加到stringbuf

// stringbuf.cpp

#include <sstream>
#include <iostream>

using namespace std;

size_t receive(uint8_t* buffer, size_t size)
{
    return fread(buffer, 1, size, stdin);
}

int main()
{
    stringbuf _inputBuf;

    size_t total = 0;
    uint8_t buffer[1000];

    // receive from source
    size_t received = receive(buffer, sizeof(buffer));
    while (received > 0)
    {
        total += received;

        // put received bytes in the stringbuf
        size_t writen = 0;
        while (writen < received)
        {
            writen += _inputBuf.sputn(
                          (const char*)buffer + writen,
                          received - writen);
        }

        // get the next chunk
        received = receive(buffer, sizeof(buffer));
    }

    // report
    if (total > 0)
    {
        cout 
            << to_string(total) + " incoming bytes" 
            << endl;

        cout 
            << to_string(_inputBuf.in_avail()) + " bytes put in buffer"
            << endl;
    }
}

报告示例接收20000个字符:

$ g++ stringbuf.cpp
$ yes 1 | dd status=none bs=1 count=20000 | ./a.out 
20000 incoming bytes
16385 bytes put in buffer

传入的总数是正确的,但是第一次迭代就没有缓冲。

在更多的迭代中执行此代码,结果是按预期的结果,而传入的字节数不大于上次调整的容量(这是猜测,似乎遵循该模式)。

  • 是否可以设置初始stringbuf容量?

  • 该代码在哪里失败?

0 个答案:

没有答案