The following code compiles and runs fine, but does not work as intended (compare the comments in the code). I believe the reason is that the lifetime of is ends with getFileIter, so the stream buffer iterator has nothing left to iterate over. (By contrast, I think I remember that in C#, is would live as long as the stream buffer iterator points to it, but that does not seem to be the case in C++.)
One fix to avoid this is using ... *is = new std::ifstream(p), but this means I have to take care of the pointer myself when I'm done.
Is there any mechanism to link the lifetimes of is and its stream buffer iterator?
// g++ test.cpp -o test && ./test
#include <iostream>
#include <fstream>
std::istreambuf_iterator<char> getFileIter(std::string p)
{
std::ifstream is(p);
//std::ifstream *is = new std::ifstream(p);
std::cout << "Read " << p << "? " << is.good() << std::endl;
return std::istreambuf_iterator<char>(is.rdbuf());
}
int main()
{
std::string p1("/etc/passwd");
std::string p2("/etc/group");
// Prints 1 as if the two files were identical
std::cout << std::equal(
getFileIter(p1),
std::istreambuf_iterator<char>(),
getFileIter(p2)
) << std::endl;
// Prints nothing except /////
auto x = getFileIter(p1);
int i = 0;
do
{
std::cout << *(x++) << "/";
i++;
} while (i < 5);
std::cout << std::endl;
return 0;
}