Gathering the contents of a .txt file as a string, C++

I currently have a little program here that will rewrite the contents of a .txt file as a string.

However I'd like to gather all the contents of the file as a single string, how can I go about this?

#include <iostream>
#include <fstream>
#include <string>


using namespace std;


int main () {
    string file_name ; 


    while (1 == 1){
        cout << "Input the directory or name of the file you would like to alter:" << endl;
        cin >>  file_name ;


        ofstream myfile ( file_name.c_str() );
        if (myfile.is_open())
        {
        myfile << "123abc";

        myfile.close();
        }
        else cout << "Unable to open file" << endl;


    }


}

Answers


The libstdc++ guys have a good discussion of how to do this with rdbuf.

The important part is:

std::ifstream in("filename.txt");
std::ofstream out("filename2.txt");

out << in.rdbuf();

I know, you asked about putting the contents into a string. You can do that by making out a std::stringstream. Or you can just add it to a std::string incrementally with std::getline:

std::string outputstring;
std::string buffer;
std::ifstream input("filename.txt");

while (std::getline(input, buffer))
    outputstring += (buffer + '\n');

#include <sstream>
#include <string>

std::string read_whole_damn_thing(std::istream & is)
{
    std::ostringstream oss;
    oss << is.rdbuf();
    return oss.str();
}

You declare a string and a buffer and then read the file with a while not EOF loop and add buffer to string.


Need Your Help

Are there any cases where java “platform agnosticism” may fail?

java compilation platform-agnostic

I have been using java for long time but this question came to my mind recently and has been troubling me since.

Jenkins behind Apache Server / Can't log in Jenkins

apache login jenkins

I'm running an Apache Server 2.2 to handle Jenkins and SonaType Nexus information (both installed as Windows Service). While SonatypeNexus runs perfectly Jenkins doesn't. To be more specific: I'can...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.