What is the most elegant way to read a text file with c++?

前端 未结 5 1116
广开言路
广开言路 2020-11-28 00:49

I\'d like to read whole content of a text file to a std::string object with c++.

With Python, I can write:

text = open(\"text.txt\", \"         


        
5条回答
  •  生来不讨喜
    2020-11-28 01:21

    There are many ways, you pick which is the most elegant for you.

    Reading into char*:

    ifstream file ("file.txt", ios::in|ios::binary|ios::ate);
    if (file.is_open())
    {
        file.seekg(0, ios::end);
        size = file.tellg();
        char *contents = new char [size];
        file.seekg (0, ios::beg);
        file.read (contents, size);
        file.close();
        //... do something with it
        delete [] contents;
    }
    

    Into std::string:

    std::ifstream in("file.txt");
    std::string contents((std::istreambuf_iterator(in)), 
        std::istreambuf_iterator());
    

    Into vector:

    std::ifstream in("file.txt");
    std::vector contents((std::istreambuf_iterator(in)),
        std::istreambuf_iterator());
    

    Into string, using stringstream:

    std::ifstream in("file.txt");
    std::stringstream buffer;
    buffer << in.rdbuf();
    std::string contents(buffer.str());
    

    file.txt is just an example, everything works fine for binary files as well, just make sure you use ios::binary in ifstream constructor.

提交回复
热议问题