Getting desired binary data ranges from std::istreambuf_iterator and std::ifstream

前端 未结 2 696
感动是毒
感动是毒 2020-12-22 03:47
#include 
#include 
#include 
#include 

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


        
2条回答
  •  隐瞒了意图╮
    2020-12-22 04:19

    Here's my recommended Spirit approach:

    #include 
    #include 
    
    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 buffer;
        bool ok = qi::parse(f, l, *qi::word, buffer);
    }
    

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

    • http://www.boost.org/doc/libs/1_52_0/libs/spirit/doc/html/spirit/qi/reference/binary/binary_native.html
    • http://www.boost.org/doc/libs/1_52_0/libs/spirit/doc/html/spirit/qi/reference/binary/binary_little.html
    • http://www.boost.org/doc/libs/1_52_0/libs/spirit/doc/html/spirit/qi/reference/binary/binary_big.html

    You can look at wchar_t

    #include 
    #include 
    #include 
    #include 
    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 buffer;
        std::copy( 
                std::istreambuf_iterator( file ),
                std::istreambuf_iterator(),
                std::back_inserter( buffer )
                );
    }
    

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

提交回复
热议问题