ifstream::rdbuf()到底是干什么的?

问题描述 投票:19回答:3

我有下面的代码,它工作得很好(除了它很慢,但我不太关心这个)。这似乎并不直观,这将把infile的全部内容写到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;
}

有什么见解吗?

c++ ifstream
3个回答
19
投票

是的,在标准中规定了,而且实际上很简单。rdbuf() 只是返回一个指向底层 basic_streambuf 对象的 [io]stream 对象的重载。

basic_ostream<...> 有一个重载,用于 operator<< 的指针。basic_streambuf<...> 的内容,写出 basic_streambuf<...>.


23
投票

iostream 类只是IO缓冲区的封装器。缓冲区的 iostream 本身并没有做很多事情......主要是,它提供的是 operator>> 格式化运算符。缓冲区是由一个从 basic_streambuf,您可以使用 rdbuf().

basic_streambuf 是一个抽象的基础,有许多虚拟函数,这些函数被重载,为读写文件、字符串等提供统一的接口。函数 basic_ostream<…>::operator<<( basic_streambuf<…> ) 被定义为不断读取缓冲区,直到底层数据源耗尽。

iostream 是一个可怕的混乱,虽然。


1
投票

快速浏览一下源代码就会发现 basic_ofstream 是围绕 basic_filebuf.

© www.soinside.com 2019 - 2024. All rights reserved.