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

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

    Never write into the std::string's const char * buffer. Never ever! Doing so is a massive mistake.

    Reserve() space for the whole string in your std::string, read chunks from your file of reasonable size into a buffer, and append() it. How large the chunks have to be depends on your input file size. I'm pretty sure all other portable and STL-compliant mechanisms will do the same (yet may look prettier).

提交回复
热议问题