tags:

views:

126

answers:

4

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?

+1  A: 
ifstream f("transit_test.py", ios_base::in | ios_base::binary);
f.seekg(0, ios::end);
int len = f.tellg();
f.seekg(0, ios::beg);
char* s = new char[len];
f.read(s, len);
f.close();
Mark H
At least use a STD::vector rather than newing a char array. This is not exception safe and your code is already leaking. If in doubt do not use pointers that are not wrapped in a class ( like STD::vector)
Martin York
+7  A: 

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>());
Don Reba
Won't that only work for wide-character encodings?
Arafangion
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
Not the most efficient way of doing it, but it should work
Martin York
+1  A: 

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;
}
Prabhu Jayaraman
Along with being relatively long, this is buggy: it'll typically appear to read the last line twice (`while (!in.eof())` is pretty much a guaranteed bug).
Jerry Coffin
Never put the test for eof in the while condition.
Martin York
+4  A: 

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
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
@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
Probably true. :-)
Martin York