Reading contents of a file to a vector at one go!

It’s quite easy to read the contents of a file to a vector at one go. For this we need to get the size of a file and ask vector to allocate a buffer to hold these many bytes (use vector::resize()). Here is a function which does this. Note that it’s a byte/char vector.

[sourcecode language=’cpp’]#include “vector”
#include “fstream”

void ReadFileToVector( const char* FileName, std::vector& FileBuff )
{
   using namespace std;

   ifstream ifile;
   ifile.open( FileName, ios::in );

   // Get file size
   ifile.seekg(0, ios_base::end);
   streamoff FileSize = ifile.tellg();
   ifile.seekg(0, ios_base::beg);

   // Resize vector to file size
   FileBuff.resize( FileSize, 0 );
   // Read in file contents to buffer
   ifile.read(&FileBuff[0], FileSize);
}[/sourcecode]

Benefit of using a vector instead of a char pointer is that we don’t have to do memory management and also we are directly accessing this buffer so no reallocations occur internally but we’ll have to check for allocation failure after calling vector::resize since files can be of huge sizes. You can optimize this further, post a comment if you find any issue/optimization. Also note that there are other ways to achieve the same behavior for e.g. using istream_iterator and back_inserter but this does cause frequent reallocations in a vector IMO making things slower.

Appreciate your comments...