C++ ifstream::rdbuf() 实际上是做什么的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2141749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does ifstream::rdbuf() actually do?
提问by Brian T Hannan
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?
任何见解?
采纳答案by CB Bailey
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()
只返回一个指向给basic_streambuf
定[io]stream
对象的底层对象的指针。
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<...>
.
回答by Potatoswatter
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()
.
iostream
类只是 I/O 缓冲区的包装器。它iostream
本身并没有做很多事情……主要是它提供了operator>>
格式化操作符。缓冲区由派生自 的对象提供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
然而,这是一个可怕的混乱。