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?
istream_iterator wants basic_istream as argument.operator>> inside basic_istream class.operator>> will lead to compile time conflicts with class member operator>>.basic_istream for type uint32_t. But for specialization you should rewrite all fuctionons of basic_istream class. Instead you could define dummy class x and specialize basic_istream for it as in the following code:using namespace std;
struct x {};
namespace std {
template<class traits>
class basic_istream<x, traits> : public basic_ifstream<uint32_t>
{
public:
explicit basic_istream<x, traits>(const wchar_t* _Filename,
ios_base::openmode _Mode,
int _Prot = (int)ios_base::_Openprot) : basic_ifstream<uint32_t>( _Filename, _Mode, _Prot ) {}
basic_istream<x, traits>& operator>>(uint32_t& data)
{
read(&data, 1);
return *this;
}
};
} // namespace std
int main()
{
basic_istream<x> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, x>( file ), istream_iterator<uint32_t, x>() );
cout << buffer.size() << endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With