How do I read an entire file into a std::string in C++?

后端 未结 15 1937
余生分开走
余生分开走 2020-11-21 23:51

How do I read a file into a std::string, i.e., read the whole file at once?

Text or binary mode should be specified by the caller. The solution should b

15条回答
  •  你的背包
    2020-11-22 00:11

    Something like this shouldn't be too bad:

    void slurp(std::string& data, const std::string& filename, bool is_binary)
    {
        std::ios_base::openmode openmode = ios::ate | ios::in;
        if (is_binary)
            openmode |= ios::binary;
        ifstream file(filename.c_str(), openmode);
        data.clear();
        data.reserve(file.tellg());
        file.seekg(0, ios::beg);
        data.append(istreambuf_iterator(file.rdbuf()), 
                    istreambuf_iterator());
    }
    

    The advantage here is that we do the reserve first so we won't have to grow the string as we read things in. The disadvantage is that we do it char by char. A smarter version could grab the whole read buf and then call underflow.

提交回复
热议问题