0

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;


    }


}
Amro
  • 121,265
  • 25
  • 232
  • 431
rectangletangle
  • 42,965
  • 86
  • 186
  • 264

5 Answers5

6
#include <sstream>
#include <string>

std::string read_whole_damn_thing(std::istream & is)
{
    std::ostringstream oss;
    oss << is.rdbuf();
    return oss.str();
}
Benjamin Lindley
  • 95,516
  • 8
  • 172
  • 256
5

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

Stefan Steiger
  • 68,404
  • 63
  • 337
  • 408
4

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');
Max Lybbert
  • 18,615
  • 3
  • 41
  • 68
3
string stringfile, tmp;

ifstream input("sourcefile.txt");

while(!input.eof()) {
    getline(input, tmp);
    stringfile += tmp;
    stringfile += "\n";
}

If you want to do it line by line, just use a vector of strings.

Paresh Mayani
  • 122,920
  • 69
  • 234
  • 290
1

You can also iterate and read through the file while assigning each character to a string until the EOF is reached.

Here is a sample:

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    char xit;
    char *charPtr = new char();
    string out = "";
    ifstream infile("README.txt");

    if (infile.is_open())
    {
        while (!infile.eof())           
        {
            infile.read(charPtr, sizeof(*charPtr));
            out += *charPtr;
        }
        cout << out.c_str() << endl;
        cin >> xit;
    }
    return 0;
}
TheWolf
  • 1,553
  • 3
  • 20
  • 32