Converting an entire text file to a string

Been looking on the internet and have been unable to locate anything to help me with this (that is clear cut to the point where I can understand it at least).


1
2
3
4
5
6
7
ifstream AAA ("BBB.txt");

if (AAA.is_open())
{
std::string part1;
}


This is just a snippet of the code. All I want to do is find the command(s) necessary to convert the entire text file into the string I've called "part1". That's it. The text file is actually an html website saved to a text file, but I want to convert it to a string and manipulate it from there but I don't know the command to convert the entire text file (which may vary in size) into a single string.
1
2
3
4
5
int character;
while((character = AAA.get()) != EOF) //while we haven't reach the end of the file
{
  part1 += char(character); //add the character to the string
}
There are many ways to do it (aren't there always?)

I like range-construction:

1
2
3
std::ifstream AAA("BBB.txt");
std::istreambuf_iterator<char> beg(AAA), end;
std::string part1(beg, end);

By chance, I spotted this function in a Boost sample shortly after I originally glanced at this thread:

1
2
3
4
5
6
7
8
9
10
11
12
13
void load_file(std::string& s, std::istream& is)
{
   s.erase();
   if(is.bad()) return;
   s.reserve(is.rdbuf()->in_avail());
   char c;
   while(is.get(c))
   {
      if(s.capacity() == s.size())
         s.reserve(s.capacity() * 3);
      s.append(1, c);
   }
}


It's from Boost.Regex's regex_grep_example_1.cpp, by Dr John Maddock

Andy

Topic archived. No new replies allowed.