Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ifstream::rdbuf() actually do?

Tags:

c++

ifstream

I have the following code and it works pretty good (other than the fact that it's pretty slow, but I don't care much about that). It doesn't seem intuitive that this would write the entire contents of the infile to the outfile.

// Returns 1 if failed and 0 if successful
int WriteFileContentsToNewFile(string inFilename, string outFilename)
{
    ifstream infile(inFilename.c_str(), ios::binary);
    ofstream outfile(outFilename.c_str(), ios::binary);

    if( infile.is_open() && outfile.is_open() && infile.good() && outfile.good() )
    {
        outfile << infile.rdbuf();

        outfile.close();
        infile.close();
    }
    else
        return 1;

    return 0;
}

Any insight?

like image 862
Brian T Hannan Avatar asked Jan 26 '10 18:01

Brian T Hannan


3 Answers

iostream classes are just wrappers around I/O buffers. The iostream itself doesn't do a whole lot… mainly, it the provides operator>> formatting operators. The buffer is provided by an object derived from basic_streambuf, which you can get and set using rdbuf().

basic_streambuf is an abstract base with a number of virtual functions which are overridden to provide a uniform interface for reading/writing files, strings, etc. The function basic_ostream<…>::operator<<( basic_streambuf<…> ) is defined to keep reading through the buffer until the underlying data source is exhausted.

iostream is a terrible mess, though.

like image 76
Potatoswatter Avatar answered Nov 15 '22 10:11

Potatoswatter


Yes, it's specified in the standard and it's actually quite simple. rdbuf() just returns a pointer to the underlying basic_streambuf object for the given [io]stream object.

basic_ostream<...> has an overload for operator<< for a pointer to basic_streambuf<...> which writes out the contents of the basic_streambuf<...>.

like image 42
CB Bailey Avatar answered Nov 15 '22 09:11

CB Bailey


A quick look at the source code shows that basic_ofstream is the wrapper around basic_filebuf.

like image 36
asterisk Avatar answered Nov 15 '22 09:11

asterisk