如何从std::istream中找出可用的字节数

How can I find out how many bytes are available from a std::istream?

本文关键字:字节数 std istream      更新时间:2023-10-16

如果我想将read()的内容std::istream放入缓冲区,我必须首先了解有多少数据可用,才能知道缓冲区的大小。为了从istream中获得可用字节数,我目前正在做这样的事情:

std::streamsize available( std::istream &is )
{
    std::streampos pos = is.tellg();
    is.seekg( 0, std::ios::end );
    std::streamsize len = is.tellg() - pos;
    is.seekg( pos );
    return len;
}

类似地,由于std::istream::eof((不是一个非常有用的基础AFAICT,为了查明istream的get指针是否在流的末尾,我这样做:

bool at_eof( std::istream &is )
{
    return available( is ) == 0;
}

我的问题:

有没有更好的方法可以从istream中获得可用字节数?如果不在标准库中,也许在boost中?

对于std::cin,您不需要担心缓冲,因为它已经被缓冲了——而且您无法预测用户敲击了多少键。

对于打开的二进制std::ifstream(也是缓冲的(,可以调用seekg(0, std::ios:end)tellg()方法来确定有多少字节。

您也可以在阅读以下内容后调用gcount()方法:

char buffer[SIZE];
while (in.read(buffer,SIZE))
{
  std::streamsize num = in.gcount();
  // call your API with num bytes in buffer 
}

对于文本输入,通过std::getline(inputstream, a_string)阅读并随后分析该字符串可能很有用。

将其作为答案发布,因为这似乎是OP想要的。

我必须先找出有多少数据可用,才能知道缓冲区有多大——这不是真的。请看我的答案(第二部分(。