Re: output_iterator_tag and back_insert_iterator
In article <y1rzlpfeeur.fsf@ics.uci.edu>, rares@ics.uci.edu says...
[ ... ]
I defined the following function:
template<class T>
void readBinaryFile(
const std::string &filename,
std::iterator<std::output_iterator_tag, T> data)
{
...
}
That was your first mistake... :-)
Because the function is reading binary data, it needs to know the type of
the elements in the container, T.
Yup.
The function want is already implemented. It's called std::copy.
All you need to do is write an extractor that extracts an item from your
file correctly. The one problem is that there are already overloads to
read the data incorrectly (i.e. from a text file) for many built-in
types. You can overcome this by creating a proxy class, something like:
template <class T>
class binIO {
T data;
public:
operator T() const { return data; }
binIO(T value = T()) : data(value) { }
friend std::istream &operator>>(std::istream &is, binIO &f) {
return is.read((char *)&f.data, sizeof(f.data));
}
friend std::ostream &operator<<(std::ostream &os, binIO const &f) {
return os.write((char *)&f.data, sizeof(f.data));
}
};
To read (for example) a file of floats in binary format into a vector,
you'd do something like:
std::vector<float> data;
std::ifstream in("input.dat", std::ios::binary);
std::copy(std::istream_iterator<binIO<float> >(in),
std::istream_iterator<binIO<float> >(),
std::back_inserter(data));
--
Later,
Jerry.
The universe is a figment of its own imagination.