D R
D R

Reputation: 22500

Reading a file to a string in C++

As somebody who is new to C++ and coming from a python background, I am trying to translate the code below to C++

f = open('transit_test.py')
s = f.read()

What is the shortest C++ idiom to do something like this?

Upvotes: 3

Views: 1170

Answers (3)

Don Reba
Don Reba

Reputation: 14051

The C++ STL way to do this is this:

#include <string>
#include <iterator>
#include <fstream>

using namespace std;

wifstream f(L"transit_test.py");
wstring s(istreambuf_iterator<wchar_t>(f), (istreambuf_iterator<wchar_t>()) );

Upvotes: 6

Jerry Coffin
Jerry Coffin

Reputation: 490623

I'm pretty sure I've posted this before, but it's sufficiently short it's probably not worth finding the previous answer:

std::ifstream in("transit_test.py");
std::stringstream buffer;

buffer << in.rdbuf();

Now buffer.str() is an std::string holding the contents of transit_test.py.

Upvotes: 6

josh
josh

Reputation: 14443

You can do file read in C++ as like,

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

int main ()
{
    string line;
    ifstream in("transit_test.py"); //open file handler
    if(in.is_open()) //check if file open
    {
        while (!in.eof() ) //until the end of file
        {
            getline(in,line); //read each line
            // do something with the line
        }
        in.close(); //close file handler
    }
    else
    {
         cout << "Can not open file" << endl; 
    }
    return 0;
}

Upvotes: -3

Related Questions