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

后端 未结 15 1934
余生分开走
余生分开走 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:04

    #include 
    #include 
    
    using namespace std;
    
    string GetStreamAsString(const istream& in)
    {
        stringstream out;
        out << in.rdbuf();
        return out.str();
    }
    
    string GetFileAsString(static string& filePath)
    {
        ifstream stream;
        try
        {
            // Set to throw on failure
            stream.exceptions(fstream::failbit | fstream::badbit);
            stream.open(filePath);
        }
        catch (system_error& error)
        {
            cerr << "Failed to open '" << filePath << "'\n" << error.code().message() << endl;
            return "Open fail";
        }
    
        return GetStreamAsString(stream);
    }
    

    usage:

    const string logAsString = GetFileAsString(logFilePath);
    

提交回复
热议问题