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?

3
  • 3
    you're just trying to showoff! :/ Commented Jul 20, 2010 at 3:45
  • 1
    @JohnB: Or looking for sympathy? Commented Jul 20, 2010 at 4:01
  • 1
    I don't think reading a file is "showing off". Commented Jul 20, 2010 at 4:33

3 Answers 3

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>()) );
Sign up to request clarification or add additional context in comments.

3 Comments

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.
R s(T(f), T()); is a function declaration.
@Abyx: R s(T(f), (T()) ); isn't. ;)
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.

2 Comments

Does that not cause a redundant copy? How about this. stackoverflow.com/questions/132358/…
@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.
-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;
}

2 Comments

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).
Never put the test for eof in the while condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.