I have a big file full of integers that I\'m loading in. I\'ve just started using C++, and I\'m trying out the filestream stuff. From everything I\'ve read, it appears I c
To read by 4 bytes from ifstream
you could overload operator>>
as follows (it is actually a partial specialization of the basic_istream
class template so istream_iterator
could use operator>>
from it. Class basic_ifstream
is used here to inherit all input file stream functionality from it):
#include
typedef unsigned int uint32_t;
struct uint32_helper_t {};
namespace std {
template
class basic_istream : public basic_ifstream {
public:
explicit basic_istream(const char* filename,
ios_base::openmode mode ) : basic_ifstream( filename, mode ) {}
basic_istream& operator>>(uint32_t& data) {
read(&data, 1);
return *this;
}
};
} // namespace std {}
Then you could use it in the following way:
std::basic_istream my_file( FILENAME, std::ios::in|std::ios::binary );
// read one int at a time
uint32_t value;
my_file >> value;
// read all data in file
std::vector data;
data.assign( std::istream_iterator(my_file),
std::istream_iterator() );