0

Possible Duplicate:
What is the best way to slurp a file into a std::string in c++?

Im trying to store a whole text file as a string, how can I dynamically store any amount of characters the text file may contain?

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
theUser
  • 1,196
  • 2
  • 19
  • 39
  • What's the size of your file like? 20GB? – P.P Nov 05 '12 at 22:08
  • 2
    possible duplicate of [What is the best way to slurp a file into a std::string in c++?](http://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c) or [What is the most elegant way to read a text file with c++](http://stackoverflow.com/questions/195323/what-is-the-most-elegant-way-to-read-a-text-file-with-c) – Blastfurnace Nov 05 '12 at 22:10
  • @KingsIndian, Nothing more than a few kilobytes – theUser Nov 05 '12 at 22:10

2 Answers2

8

The C++ Standard Library provides the std::string type for dynamically sized strings. It is a typedef for std::basic_string<char>. There's a useful reference at cppreference.com.

For reading lines from a file into a std::string, take a look at std::getline. You can use it to get a line from a file as follows:

std::string str;
std::getline(file_stream, str);

Be sure to check the stream (it is returned by std::getline) to see if everything went okay. This is often done in a loop:

while (std::getline(file_stream, str)) {
  // Use str
}
Joseph Mansfield
  • 100,738
  • 18
  • 225
  • 303
3

In addition to sftrabbit's answer:

Note that you can read a whole file into a string in one go by doing this:

std::ifstream input_ifstr(filename.c_str());

std::string str(
    (std::istreambuf_iterator<char>(input_ifstr)),
    std::istreambuf_iterator<char>());

input_ifstr.close();

You can construct a stringstream from it to process with getline afterwards if you wish.

user673679
  • 1,196
  • 1
  • 16
  • 32