简体   繁体   English

ifstream::rdbuf() 实际上是做什么的?

[英]What does ifstream::rdbuf() actually do?

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.将 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;
}

Any insight?任何见解?

iostream classes are just wrappers around I/O buffers. iostream类只是 I/O 缓冲区的包装器。 The iostream itself doesn't do a whole lot… mainly, it the provides operator>> formatting operators. iostream本身并没有做很多事情……主要是,它提供了operator>>格式化操作符。 The buffer is provided by an object derived from basic_streambuf , which you can get and set using rdbuf() .缓冲区由从basic_streambuf派生的对象提供,您可以使用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. basic_streambuf是一个抽象基础,具有许多虚函数,这些虚函数被覆盖以提供用于读/写文件、字符串等的统一接口。函数basic_ostream<…>::operator<<( basic_streambuf<…> )被定义为保持读取缓冲区,直到底层数据源耗尽。

iostream is a terrible mess, though. iostream是一团糟。

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. rdbuf()只是返回一个指向给定[io]stream对象的基础basic_streambuf对象的指针。

basic_ostream<...> has an overload for operator<< for a pointer to basic_streambuf<...> which writes out the contents of the basic_streambuf<...> . basic_ostream<...>具有用于过载operator<<指针是指向basic_streambuf<...>其中写出的内容basic_streambuf<...>

快速查看源代码表明basic_ofstreambasic_filebuf的包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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