繁体   English   中英

在C ++中输出ofstream的filebuf *有什么作用?

[英]What does outputting the filebuf* of an ofstream in C++ do?

使用ifstream我们可以将整个文件输出到cout如下所示:

std::ifstream foo("testfile");
std::cout << foo.rdbuf();

但是,当我们尝试对ofstream进行相同操作时会发生什么?

std::ofstream foo("testfile", std::ios::app); // use app to avoid wiping out contents of testfile
std::cout << foo.rdbuf();

对我来说,它什么都不输出。

是否将ofstreamfilebuf*传递给std::cout::operator<<只是没有实际用途的无用可能性? 还是有我不知道的东西?

当执行operator <<作为未格式化数据插入streambuf重载时,将流缓冲区拉到达到eof为止,但是没有什么可以开始的,所以...

结果是将写入零个字符。 根据标准(C ++ 14§27.7.3.6.3 / 9),在这种情况下,它在目标输出流上设置的故障位由以下内容证明:

#include <iostream>
#include <fstream>
#include <iomanip>

int main()
{
    std::ofstream foo("testfile", std::ios::app);
    std::cerr << std::boolalpha << std::cout.fail() << '\n';
    std::cout << foo.rdbuf();
    std::cerr << std::boolalpha << std::cout.fail() << '\n';
}

输出量

false
true

是的,在这种情况下,它不仅是无用的,而且还会使目标ostream失效,直到其ostream -state)被clear()

祝你好运。

暂无
暂无

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

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