从std :: istreambuf_iterator和std :: ifstream获取所需的二进制数据 [英] Getting desired binary data ranges from std::istreambuf_iterator and std::ifstream

查看:91
本文介绍了从std :: istreambuf_iterator和std :: ifstream获取所需的二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

int main()
{
    std::ifstream file("data.bin", std::ios::binary );

    if( file.fail() )
    {
        std::cout << "File does not exist or could not open file";

        return 0;
    }

    std::vector<short> buffer;

    std::copy( 
            std::istreambuf_iterator<char>( file ),
            std::istreambuf_iterator<char>(),
            std::back_inserter( buffer )
            );

   return 0;
}

这只给我char值的范围(-128、128).

This only gives me ranges of char values (-128, 128).

我认为使用 istreambuf_iterator< short> 会给我我想要的东西,但是会引发无效转换"错误.

I thought using istreambuf_iterator<short> would give me what I want but it throws an "invalid conversion" error.

如何读取 short 范围内的二进制值?

What can I do to read binary values that are in the short range?

推荐答案

以下是我推荐的Spirit方法:

Here's my recommended Spirit approach:

#include <fstream>
#include <boost/spirit/include/qi.hpp>

namespace qi = boost::spirit::qi;

int main()
{
    std::ifstream file("data.bin", std::ios::binary);
    if(!file)
        std::cout << "File does not exist or could not open file";
    boost::spirit::istream_iterator f(file), l;

    std::vector<int16_t> buffer;
    bool ok = qi::parse(f, l, *qi::word, buffer);
}

当然,有 qi :: dword qi :: qword ,big-endian/little-endian变异等.

Of course, there is qi::dword, qi::qword, big-endian/little-endian variatations etc.:

您可以看一下wchar_t

You can look at wchar_t

#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
int main()
{
    std::wifstream file("data.bin", std::ios::binary );
    if( file.fail() )
    {
        std::cout << "File does not exist or could not open file";
        return 0;
    }
    std::vector<wchar_t> buffer;
    std::copy( 
            std::istreambuf_iterator<wchar_t>( file ),
            std::istreambuf_iterator<wchar_t>(),
            std::back_inserter( buffer )
            );
}

我不太确定wchar_t的实际大小是否由实现定义.

I'm not too sure whether the actual size of wchar_t is implementation defined.

这篇关于从std :: istreambuf_iterator和std :: ifstream获取所需的二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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