Search code examples
c++stringfile-iotext-filesfile-read

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;


    }


}

Solution

  • 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');