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

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

    You can use the 'std::getline' function, and specify 'eof' as the delimiter. The resulting code is a little bit obscure though:

    std::string data;
    std::ifstream in( "test.txt" );
    std::getline( in, data, std::string::traits_type::to_char_type( 
                      std::string::traits_type::eof() ) );
    

提交回复
热议问题