I was advised a while ago that is was common place to use std::vector as exception safe dynamic array in c++ rather than allocating raw arrays... for exampl
This brought an interesting question to my mind, which I promptly asked here. In your case, you can avoid using pointers the following way:
template
OutputIterator copy_n( InputIterator first, InputIterator last, OutputIterator result, std::size_t n)
{
for ( std::size_t i = 0; i < n; i++ ) {
if (first == last)
break;
else
*result++ = *first++;
}
return result;
}
std::ifstream file("path_to_file");
std::vector buffer(n);
copy_n(std::istream_iterator(file),
std::istream_iterator(),
std::back_insert_iterator >(buffer),
n);
This will copy the contents of the file to a buffer n
chars at a time. When you iterate over the buffer, use:
for (std::vector::iterator it = buffer.begin(); it != buffer.end(); it++)
instead of a counter.