I have been working on a piece of code that reads data from a binary file using the std::ifstream class. While working on the code, I couldn't help but feel that there must be a more convenient way to work with binary files, so I came up with this little class:
class BinaryFile : public std::ifstream {
public:
explicit BinaryFile(const std::string &name):std::ifstream(name.c_str(), std::ios::binary) {}
void readChunk(void *data, int size) {
std::ifstream::read((char*)data, size);
}
// This hides the base class version of read()
template <class T>
void read(T &data, int count = 1) {
readChunk(&data, count * sizeof(T));
}
template <class T>
void read(std::vector<T> &vec, int count) {
vec.resize(count);
read(vec[0], count);
}
};
Using this class, the following code:
ifstream file("file.dat", ios::binary);
int i;
file.read((char*)&i, sizeof(int));
float f[50];
file.read((char*)&f, 50 * sizeof(float));
vector<double> vec;
vec.resize(20);
file.read((char*)&vec[0], 20 * sizeof(double));
becomes this:
BinaryFile file("file.dat");
int i;
file.read(i);
float f[50];
file.read(f, 50);
vector<double> vec;
file.read(vec, 20);
Much more convenient and less error-prone.
Hopefully this code will be useful to someone. Any comments are appreciated.
Also, is there a library that achieves something similar?
EDIT: Ironically, I just now thought about looking at boost.serialization, which seems to have the benefits of my class, and much more. I suppose the only possible advantages of my class are simplicity and shorter compile times (I heard that boost.serialization significantly increases compile times). Of course, boost.serialization achieves a completely different goal (namely, serialization), so the comparison is rather stupid, but for the simple task of reading binary files, the above advantages may be relevant.
Still, any comments are appreciated, and I still hope that someone will find this useful.
[Edited by - Gage64 on February 7, 2008 7:34:16 AM]