Load binary file using fstream

Posted by Kirill V. Lyadvinsky on Stack Overflow See other posts from Stack Overflow or by Kirill V. Lyadvinsky
Published on 2009-07-20T18:01:15Z Indexed on 2010/06/18 4:13 UTC
Read the original article Hit count: 376

Filed under:
|
|
|
|

I'm trying to load binary file using fstream in the following way:

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

using namespace std;

int main()
{
    basic_fstream<uint32_t> file( "somefile.dat", ios::in|ios::binary );

    vector<uint32_t> buffer;
    buffer.assign( istream_iterator<uint32_t, uint32_t>( file ), istream_iterator<uint32_t, uint32_t>() );

    cout << buffer.size() << endl;

    return 0;
}

But it doesn't work. In Ubuntu it crashed with std::bad_cast exception. In MSVC++ 2008 it just prints 0.

I know that I could use file.read to load file, but I want to use iterator and operator>> to load parts of the file. Is that possible? Why the code above doesn't work?

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl