This answer points out the fact that C++ is not well suited for the iteration over a binary file, but this is what I need right now, in short I need to operate on files in a "binary" way, yes all files are binary even the .txt ones, but I'm writing something that operates on image files, so I need to read files that are well structured, were the data is arranged in a specific way.
I would like to read the entire file in a data structure such as std::vector<T>
so I can almost immediately close the file and work with the content in memory without caring about disk I/O anymore.
Right now, the best way to perform a complete iteration over a file according to the standard library is something along the lines of
std::ifstream ifs(filename, std::ios::binary);
for (std::istreambuf_iterator<char, std::char_traits<char> > it(ifs.rdbuf());
it != std::istreambuf_iterator<char, std::char_traits<char> >(); it++) {
// do something with *it;
}
ifs.close();
or use std::copy
, but even with std::copy
you are always using istreambuf
iterators ( so if I understand the C++ documentation correctly, you are basically reading 1 byte at each call with the previous code ).
So the question is: how do I write a custom iterator ? from where I should inherit from ?
I assume that this is also important while writing a file to disk, and I assume that I could use the same iterator class for writing, if I'm wrong please feel free to correct me.