逐字节读取二进制istream [英] Reading binary istream byte by byte

查看:260
本文介绍了逐字节读取二进制istream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用ifstream逐字节读取二进制文件.我之前曾使用过像get()这样的istream方法来一次读取二进制文件的整个块,而不会出现问题.但是我当前的任务是使自己逐字节运行,并依靠io系统中的缓冲来使其高效.问题在于,我似乎比原先快了几个字节到达文件末尾.因此,我编写了以下测试程序:

I was attempting to read a binary file byte by byte using an ifstream. I've used istream methods like get() before to read entire chunks of a binary file at once without a problem. But my current task lends itself to going byte by byte and relying on the buffering in the io-system to make it efficient. The problem is that I seemed to reach the end of the file several bytes sooner than I should. So I wrote the following test program:

#include <iostream>
#include <fstream>

int main() {
    typedef unsigned char uint8;
    std::ifstream source("test.dat", std::ios_base::binary);
    while (source) {
        std::ios::pos_type before = source.tellg();
        uint8 x;
        source >> x;
        std::ios::pos_type after = source.tellg();
        std::cout << before << ' ' << static_cast<int>(x) << ' '
                  << after << std::endl;
    }
    return 0;
}

这将转储test.dat的内容,每行一个字节,显示文件前后的位置.

This dumps the contents of test.dat, one byte per line, showing the file position before and after.

果然,如果我的文件碰巧有两个字节的序列0x0D-0x0A(对应于回车和换行),则这些字节将被跳过.

Sure enough, if my file happens to have the two-byte sequence 0x0D-0x0A (which corresponds to carriage return and line feed), those bytes are skipped.

  • 我已经以二进制模式打开了流.那不应该阻止它解释行分隔符吗?
  • 提取运算符是否总是使用文本模式?
  • 从二进制istream逐字节读取字节的正确方法是什么?

Windows上的MSVC ++ 2008.

MSVC++ 2008 on Windows.

推荐答案

>>提取器用于格式化输入;他们跳过空格(由 默认).对于单字符无格式输入,可以使用 istream::get() (返回int,如果读取的是EOF失败,或者 [0,UCHAR_MAX]范围内的值)或istream::get(char&)(将 在参数中读取的字符,返回转换为 bool,如果读取成功,则为true,如果读取失败,则为false.

The >> extractors are for formatted input; they skip white space (by default). For single character unformatted input, you can use istream::get() (returns an int, either EOF if the read fails, or a value in the range [0,UCHAR_MAX]) or istream::get(char&) (puts the character read in the argument, returns something which converts to bool, true if the read succeeds, and false if it fails.

这篇关于逐字节读取二进制istream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆