rectangletangle
rectangletangle

Reputation: 52941

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;


    }


}

Upvotes: 0

Views: 4706

Answers (5)

Stefan Steiger
Stefan Steiger

Reputation: 82186

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

Upvotes: 5

TheWolf
TheWolf

Reputation: 1695

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;
}

Upvotes: 1

Max Lybbert
Max Lybbert

Reputation: 20039

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

Upvotes: 4

Benjamin Lindley
Benjamin Lindley

Reputation: 103703

#include <sstream>
#include <string>

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

Upvotes: 6

Paresh Mayani
Paresh Mayani

Reputation: 128428

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.

Upvotes: 3

Related Questions