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

后端 未结 15 1967
余生分开走
余生分开走 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条回答
  •  梦毁少年i
    2020-11-22 00:05

    Since this seems like a widely used utility, my approach would be to search for and to prefer already available libraries to hand made solutions, especially if boost libraries are already linked(linker flags -lboost_system -lboost_filesystem) in your project. Here (and older boost versions too), boost provides a load_string_file utility:

    #include 
    #include 
    #include 
    
    int main() {
        std::string result;
        boost::filesystem::load_string_file("aFileName.xyz", result);
        std::cout << result.size() << std::endl;
    }
    

    As an advantage, this function doesn't seek an entire file to determine the size, instead uses stat() internally. As a possibly negligible disadvantage though, one could easily infer upon inspection of the source code: string is unnecessarily resized with '\0' character which are rewritten by the file contents.

提交回复
热议问题