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

iezvtpos  于 2023-06-25  发布在  其他
关注(0)|答案(3)|浏览(422)

我有下面的代码,它工作得很好(除了它相当慢的事实,但我不太关心这个)。这似乎并不直观地将infile的全部内容写入outfile。

  1. // Returns 1 if failed and 0 if successful
  2. int WriteFileContentsToNewFile(string inFilename, string outFilename)
  3. {
  4. ifstream infile(inFilename.c_str(), ios::binary);
  5. ofstream outfile(outFilename.c_str(), ios::binary);
  6. if( infile.is_open() && outfile.is_open() && infile.good() && outfile.good() )
  7. {
  8. outfile << infile.rdbuf();
  9. outfile.close();
  10. infile.close();
  11. }
  12. else
  13. return 1;
  14. return 0;
  15. }

有什么见解吗?

00jrzges

00jrzges1#

是的,标准中有规定,实际上很简单。rdbuf()只是返回一个指向给定[io]stream对象的底层basic_streambuf对象的指针。
basic_ostream<...>有一个operator<<的重载,用于指向basic_streambuf<...>的指针,该指针写出basic_streambuf<...>的内容。

jhdbpxl9

jhdbpxl92#

快速查看源代码会发现basic_ofstreambasic_filebuf的 Package 器。

biswetbf

biswetbf3#

iostream类只是I/O缓冲区的 Package 器。iostream本身并没有做很多事情。主要提供operator>>化操作符。缓冲区由一个派生自basic_streambuf的对象提供,您可以使用rdbuf()获取和设置该对象。
basic_streambuf是一个抽象库,它有许多虚函数,这些虚函数被重写以提供阅读/写文件、字符串等的统一接口。函数basic_ostream<…>::operator<<( basic_streambuf<…> )被定义为不断阅读缓冲区,直到底层数据源耗尽。
iostream是一个可怕的混乱,虽然。

相关问题