简体   繁体   English

c ++从istream读取二进制数据

[英]c++ read binary data from istream

I have an istream and I have to read it into a buffer.我有一个 istream,我必须将它读入缓冲区。 I could not find a way to figure out the read_len once eof is encountered?一旦遇到 eof,我就找不到找出 read_len 的方法? I cannot use get because my file does not have delimeters.我无法使用 get,因为我的文件没有分隔符。

It seems that the only option is to read it character by character, is it really the only option?似乎唯一的选择是逐字阅读,真的是唯一的选择吗?

char buffer[128];
while(is.good()) {
     is.read(buffer, sizeof(buffer));
     size_t read_len = sizeof(buffer);
     if (is.eof()) {
         read_len = xxxx;
     }
     process(buffer, read_len);
}

You could checkistream::gcount() which " Returns the number of characters extracted by the last unformatted input operation ".您可以检查istream::gcount()其“返回上次未格式化输入操作提取的字符数”。

Example:例子:

    while(is) {
         is.read(buffer, sizeof buffer);
         auto read_len = is.gcount();  // <- 
         if(read_len > 0)
             process(buffer, read_len);
         else
             break;
    }

You could also use istream::readsome() - but note: " The behavior of this function is highly implementation-specific. " which may or may not be an issue.您也可以使用istream::readsome() - 但请注意:“此函数的行为是高度特定于实现的。 ”这可能是也可能不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM