如何从std::istream中找出可用的字节数
How can I find out how many bytes are available from a std::istream?
如果我想将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想要的。
我必须先找出有多少数据可用,才能知道缓冲区有多大——这不是真的。请看我的答案(第二部分(。
相关文章:
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 基于字节数组生成静态范围整数值
- 将字节数组转换为带有字节序问题的指针
- 使用 stbi_write_png,如何将 0 和 1 的矩形字节数组转换为单色 png 文件?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 swig 追加到字节数组
- C++ 替换字节数组中项的顺序
- QDataStream 读取和写入的字节数比 QFile::length() 报告要多
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 如何在C++(Arduino)中将浮点数组转换为字节数组
- 将字节数组转换为多维数组
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- 如何将带有空字符的字节数组馈送到 std::iostream 中?
- 比较存储在 std::string 中的数据中的字节数
- 如何跟踪写入std :: Ostream对象的字节数
- 在写入二进制文件时,“std::ofstream::write”有时会写入超出应有字节数的字节
- 可以将std::对的std::矢量转换为字节数组
- 提取跨字节数组内容到std::bitset
- 如何从std::istream中找出可用的字节数
- 将std::string转换为十六进制,然后将其存储在字节数组中