1

Apologies for the basic question; I'm relatively new to C++.

I've looked around and seen many different suggestions for how to read from a file to a char array. For example, this one creates a char array of size 10000, but this is suboptimal (either wasted space, or not enough space).

What's the simplest, and most commonly used method for reading from a file to a string, or string-like sequence? This is such a common operation; there's got to be a standard way to do it. Is there no one-liner for this?

Community
  • 1
  • 1
sgarza62
  • 5,070
  • 5
  • 37
  • 59
  • There is a similar question [here](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring). The answers discuss various methods and their performance – Danqi Wang Apr 24 '14 at 05:00

1 Answers1

4

I would use this usually (like when we're not reading thousands of files in a loop!):

std::ifstream file("data.txt"); 
std::string data {std::istreambuf_iterator<char>{file}, 
                  std::istreambuf_iterator<char>{} };

No need to use std::copy (like the other answer; now deleted!).

If you want vector, then use this instead:

std::vector<char> data {std::istreambuf_iterator<char>{file}, 
                        std::istreambuf_iterator<char>{} };

However, if you want to populate an existing std::vector (or std::string), then use insert method (both types has insert method of same signature!):

data.insert(data.end(),                           //insert at end
            std::istreambuf_iterator<char>{file}, //source begin
            std::istreambuf_iterator<char>{} );   //source end

Hope that helps.

Nawaz
  • 327,095
  • 105
  • 629
  • 812