Why does fromstream :: flush () return ostream?

I have tried:

std::ofstream outFile (fname, std::ios::binary); //... outFile.flush(); outFile.close(); 

which works great. But when I try to combine two lines, as flush returns a link:

 outFile.flush().close(); 

It gives an error:

 error: 'struct std::basic_ostream<char>' has no member named 'close' 

Then I looked at the link more closely and found out that it really returns ostream instread of ofstream ..

why is that so? Is this a bug or design?

+6
source share
1 answer

This is by design.

ostream is a class that includes writing a sequence to the associated stream buffer, which is an abstract class that is responsible for writing and reading something. It could be anything; file, console, socket, etc.

ofstream is really just a convenience class that extends ostream to 'automatically' using the type of stream buffer that writes to a file called filebuf . The only functions provided ofstream are open , is_open and close ; this is actually a simple interface for file-specific functions of the base object of the filebuf stream filebuf .

If you really want to, you can create an ostream that does the same thing as ofstream . It just requires more code and is not so pretty or explicit.

 std::filebuf f; f.open(fname, std::ios::binary); std::ostream os(&f); os.write("Hello world!", 12); os.flush(); // Error! close() isn't part of the streambuf interface, it specific to // files. os.close(); 

Basically, ofstream does not actually ofstream , so it does not implement functions like flush and write . All entries are made using the ostream class, which manages the base streambuf class, whose task is to make sure that the data has reached its intended location (i.e. the file).

+6
source

All Articles