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

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

    The shortest variant: Live On Coliru

    std::string str(std::istreambuf_iterator{ifs}, {});
    

    It requires the header .

    There were some reports that this method is slower than preallocating the string and using std::istream::read. However, on a modern compiler with optimisations enabled this no longer seems to be the case, though the relative performance of various methods seems to be highly compiler dependent.

提交回复
热议问题