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

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

    See this answer on a similar question.

    For your convenience, I'm reposting CTT's solution:

    string readFile2(const string &fileName)
    {
        ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
    
        ifstream::pos_type fileSize = ifs.tellg();
        ifs.seekg(0, ios::beg);
    
        vector bytes(fileSize);
        ifs.read(bytes.data(), fileSize);
    
        return string(bytes.data(), fileSize);
    }
    

    This solution resulted in about 20% faster execution times than the other answers presented here, when taking the average of 100 runs against the text of Moby Dick (1.3M). Not bad for a portable C++ solution, I would like to see the results of mmap'ing the file ;)

提交回复
热议问题