简体   繁体   中英

What does outputting the filebuf* of an ofstream in C++ do?

With an ifstream we can output the whole file to cout like this:

std::ifstream foo("testfile");
std::cout << foo.rdbuf();

But what happens when we try to do the same with an ofstream ?

std::ofstream foo("testfile", std::ios::app); // use app to avoid wiping out contents of testfile
std::cout << foo.rdbuf();

For me it doesn't output anything.

Is passing the filebuf* of an ofstream to std::cout::operator<< just a useless possibility that has no real usage? Or is there something about it I'm not aware of?

When executing the operator << overload for streambuf insertion as unformatted data, the stream buffer is pulled until it reaches eof, but there is nothing to get to begin with, so...

The result is zero characters will be written. Per the standard (C++14 § 27.7.3.6.3/9), in such a case the fail-bit it set on the target output stream, and is evidenced by the following:

#include <iostream>
#include <fstream>
#include <iomanip>

int main()
{
    std::ofstream foo("testfile", std::ios::app);
    std::cerr << std::boolalpha << std::cout.fail() << '\n';
    std::cout << foo.rdbuf();
    std::cerr << std::boolalpha << std::cout.fail() << '\n';
}

Output

false
true

And yes, in this case it is not only useless, it renders the target ostream useless until its fail-state is clear() ed.

Best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM