如何找出 std::istream 有多少字节可用?
如果我想将 std::istream
的内容 read()
读入缓冲区,我必须首先找出有多少数据可用,才能知道有多大来制作缓冲区。为了从 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
的获取指针位于流的末尾,我正在这样做:
bool at_eof( std::istream &is )
{
return available( is ) == 0;
}
我的问题:
是否有更好的方法从 istream
获取可用字节数?如果不在标准库中,也许在 boost 中?
If I wanted to read()
the content of a std::istream
in to a buffer, I would have to find out how much data was available first to know how big to make the buffer. And to get the number of available bytes from an istream, I am currently doing something like this:
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;
}
And similarly, since std::istream::eof() isn't a very useful fundtion AFAICT, to find out if the istream
's get pointer is at the end of the stream, I'm doing this:
bool at_eof( std::istream &is )
{
return available( is ) == 0;
}
My question:
Is there a better way of getting the number of available bytes from an istream
? If not in the standard library, in boost, perhaps?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于 std::cin ,您不需要担心缓冲,因为它已经被缓冲了 --- 并且您无法预测用户敲击了多少个键。
对于打开的二进制
std::ifstream
(也被缓冲),您可以调用seekg(0, std::ios:end)
和tellg()< /code> 方法来确定有多少字节。
您还可以在阅读后调用
gcount()
方法:对于通过
std::getline(inputstream, a_string)
读取文本输入并随后分析该字符串可能会很有用。For
std::cin
you don't need to worry about buffering because it is buffered already --- and you can't predict how many keys the user strokes.For opened binary
std::ifstream
, which are also buffered, you can call theseekg(0, std::ios:end)
andtellg()
methods to determine, how many bytes are there.You can also call the
gcount()
method after reading:For text input reading via
std::getline(inputstream, a_string)
and analyzing that string afterwards can be useful.将此作为答案发布,因为这似乎是OP想要的。
我必须首先找出有多少数据可用,才能知道缓冲区有多大 - 不正确。请参阅我的这个答案(第二部分)。
Posting this as an answer, as it seems to be what the OP wants.
I would have to find out how much data was available first to know how big to make the buffer - not true. See this answer of mine (second part).