Home > C++, VC++, STL > Reading contents of a file to a vector at one go!

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.

#include "vector"
#include "fstream"

void ReadFileToVector( const char* FileName, std::vector<char>& 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);
}

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.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: