How do you store the entire content of a file in a variable?

I would like to store the entire content of a file in a single c-string variable or in a standard string class variable. Is there a function that will do this for me? I am familiar with functions that get one character or one line at a time
but I don't think I've encountered a function that gets the entire file.
Does this function keep or disregard the end-of-line character?
If no such function exists, I would write my own function to create and return such a variable.

Thanks and grateful to have this forum - Randy
create a string

open the file

loop through the file while getline is true
add the results of getline to a string

voila entire file is in the string

here is an example of copying the contents to a vector:
1
2
3
4
5
vector<string> v;
  ifstream in("fillvector.cpp");
  string line;
  while(getline(in, line))
    v.push_back(line);
Last edited on
OK, thanks. That's about what I had in mind.
I will probably create a string s and my loop will build s by concatenate line to existing s.
Thanks
Last edited on
I would like to store the entire content of a file in a single c-string variable or in a standard string class variable.

You can use the range constructor for the string class:

1
2
3
4
5
6
7
8
9
#include <iterator>
#include <string>
#include <fstream>
int main()
{
    std::ifstream file("test.txt");
    std::istreambuf_iterator<char> beg(file), end;
    std::string data(beg, end);
}


Another handy shortcut is the command to transfer the entire contents of a file into a stringstream:

1
2
3
4
5
6
7
8
#include <sstream>
#include <fstream>
int main()
{
    std::ifstream file("test.txt");
    std::stringstream str;
    str << file.rdbuf();
}

Last edited on
Yes Cubbi. That seems to be exactly what I need. Now to understand the functions in your code. I've not heard of stringstreams before. Thank you.
Last edited on
Topic archived. No new replies allowed.