Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

C++ & STL: Reading a text file into a collection with little code

0.00/5 (No votes)
12 Apr 2011 1  
How to use istream_iterator and the copy algorithm to populate an STL collection from a text file with very little code
There is a simple function I wrote to populate an STL list with the elements in a text file. The two parameters are the filename and the list to populate. This is a template function, so it will support lists of any type of element. If you want to use a different STL collection, you can change the code from using a list to your preferred collection type. I wrote this function to clear the collection before reading the file.

The function requires the following headers and uses the following:
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iterator>
using std::ifstream;
using std::istringstream;
using std::list;
using std::for_each;
using std::istream_iterator;
using std::back_insert_iterator;


Following is the actual function. The remarkable thing about the STL is its power, and this is one example: With istream_iterator and the std::copy() function, reading the file & populating the collection can be done with very little code (practically one line).
template <class T>
void ReadDataFile(const char* pFilename, list<T>& pDataList)
{
    pDataList.clear();
    ifstream inFile(pFilename, std::ios::in);
    if (inFile.good())
    {
        std::copy(istream_iterator<T>(inFile), istream_iterator<T>(), back_insert_iterator<list<T> >(pDataList));
        inFile.close();
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here