C++ Read a whole File using ifstream

来源:互联网 发布:网络维护好学吗 编辑:程序博客网 时间:2024/06/02 03:31


std::ifstream ifs("filename.txt");

std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

Mind the extra parenthesis in the str declaration, it's necessary for correct parsing.


it's a string constructor that takes an input iterator pair. The first input iterator is an istreambuf_iterator initialized with the stream. The second input iterator is an istreambuf_iterator is default constructed. A default constructed istreambuf_iterator returns equal to another istreambuf_iterator that has exhausted the input from the streambuf it was reading from. So the constructor reads from the first istreambuf_iterator until it runs out of data.

The first argument needs to go in parenthesis otherwise the compiler will parse the string declaration as a function declaration. Specifically a function that returns a string, called str that takes as a first argument a istreambuf_iterator<char> called ifs and as a second argument an istreambuf_iterator<char> that is unnamed. Technically you can also wrap the second argument in parenthesis instead, but usually when you do it, you wrap the first one.          

0 0
原创粉丝点击