Task

Load the entire contents of some text file as a single string variable.

If applicable, discuss: encoding selection, the possibility of memory-mapping.

Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case check File IO);
this is for those cases where having the entire file is actually what is wanted.




#include <iostream>
#include <fstream>
#include <string>
#include <iterator>
 
int main( ) 
{
    if (std::ifstream infile("sample.txt"))
    {
        // construct string from iterator range
        std::string fileData(std::istreambuf_iterator<char>(infile), std::istreambuf_iterator<char>());
 
        cout << "File has " << fileData.size() << "chars\n";
 
        // don't need to manually close the ifstream; it will release the file when it goes out of scope
        return 0;
   }
   else 
   {
      std::cout << "file not found!\n";
      return 1;
   }
}
 