首页 > 解决方案 > fstream 读取 0x0A 和 0x0D 的二进制数据

问题描述

我遇到了一个我以前从未见过或以前没有注意到的奇怪问题。我正在尝试使用 ifstream 将二进制数据读入向量。我的测试代码如下所示:

#include <fstream>
#include <iostream>
#include <vector>
#include <iterator>

int main()
{
    std::ifstream ifs("foo.bin", std::ios::binary);
    ifs.seekg(0, std::ios::end);
    uint32_t size = ifs.tellg();
    ifs.seekg(0, std::ios::beg);
    std::vector<uint8_t> data;
    if (size == 0)
    {
        printf("Size can't be zero\n");
    }
    else
    {
        data.reserve(size);
        data.insert(data.begin(),
                    std::istream_iterator<uint8_t>(ifs),
                    std::istream_iterator<uint8_t>());
    }

    for (int i = 0 ; i < data.size(); i++)
    {
        std::cout << std::hex << (int)data[i] << " ";
    }
    std::cout << std::endl;
}

然后我输入一个 20 字节的二进制 blob。Hexdump 输出如下:

00000000  55 66 77 0a 99 aa 0d 30  31 33 34 00 00 11 22 33  |Ufw....0134..."3|
00000010  44 55 66 77                                       |DUfw|
00000014

我编译这个程序并运行它并得到以下18 个字节

./main 
55 66 77 99 aa 30 31 33 34 0 0 11 22 33 44 55 66 77 

注意 0x0A 和 0x0D 是如何从向量中删除的?

标签: c++

解决方案


推荐阅读