3

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?

D R
  • 21,936
  • 38
  • 112
  • 149

3 Answers3

6

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>()) );
DevSolar
  • 67,862
  • 21
  • 134
  • 209
Don Reba
  • 13,814
  • 3
  • 48
  • 61
  • Yes, it will. Unfortunately, STL does not provide an automatic way of loading files in arbitrary encodings, so you either need to know the encoding of the file in advance and adjust the code accordingly or use a library to recognize the encoding and perform the appropriate conversion. – Don Reba Jul 20 '10 at 04:37
  • 2
    `R s(T(f), T());` is a function declaration. – Abyx Jan 10 '13 at 16:50
  • @Abyx: `R s(T(f), (T()) );` isn't. ;) – DevSolar Apr 05 '13 at 18:55
6

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • Does that not cause a redundant copy? How about this. http://stackoverflow.com/questions/132358/how-to-read-file-content-into-istringstream/138645#138645 – Martin York Jul 20 '10 at 07:52
  • 1
    @Martin: It does, but unless I encountered a real problem from it (which I haven't yet), I'd tend to wonder whether attempting to avoid it wasn't a premature optimization. – Jerry Coffin Jul 20 '10 at 13:25
-3

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;
}
josh
  • 13,793
  • 12
  • 49
  • 58