Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
722 views
in Technique[技术] by (71.8m points)

c++ - Getting desired binary data ranges from std::istreambuf_iterator and 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;
}

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The class std::istreambuf_iterator<cT> iterates over the characters extracted from a std::basic_istream<cT, std::char_traits<cT>> or, actually, its std::basic_streambuf<cT, std::char_traits<cT>>. That is, given a specific stream type, there is no choice for the std::istreambuf_iterator<cT>. Also note that the IOStream layer is not intended to operate on binary files, despite the std::ios_base::binary operation which is passed to the stream buffers.

If you want to extract shorts (or any other type than the stream's character type) you'd need to create a suitable iterator yourself which takes the chosen binary format the file was written in into account. This iterator can be built in terms of std::istreambuf_iterator<char> or directly access the std::streambuf.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...