如何找出 std::istream 有多少字节可用?

发布于 2024-11-19 10:33:00 字数 645 浏览 1 评论 0原文

如果我想将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

紙鸢 2024-11-26 10:33:00

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

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

您还可以在阅读后调用 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) 读取文本输入并随后分析该字符串可能会很有用。

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 the seekg(0, std::ios:end) and tellg() methods to determine, how many bytes are there.

You can also call the gcount() method after reading:

char buffer[SIZE];

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

For text input reading via std::getline(inputstream, a_string) and analyzing that string afterwards can be useful.

¢好甜 2024-11-26 10:33:00

将此作为答案发布,因为这似乎是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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文