Reading a file into a string in C ++

As someone who is not familiar with C ++ and comes out of the python background, I am trying to translate the code below into C ++

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

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

+3
source share
3 answers

C ++ STL way to do 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>()) );
+6
source

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

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

buffer << in.rdbuf();

Now buffer.str()is std::stringcontaining the content transit_test.py.

+6
source

++, ,

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

Source: https://habr.com/ru/post/1755431/


All Articles