可以向未打开的 C++ 写入数据; ofstream 到文件?
对于未打开我的意思是:
ofstream outFile;
outFile << "Some text";
所以我将文本放入ofstream
中而不调用.open()
方法。 g++ 没有抱怨,所以也许我仍然可以保存数据?如何?
With unopened I mean:
ofstream outFile;
outFile << "Some text";
So I put text in an ofstream
without call the .open()
method. g++ does not complain, so maybe I still can save the data? How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行此操作后,流将处于失败状态(
outFile.fail()
将为 true)。该文本不存储在任何地方,所以不,您无法保存它。如果您想将数据存储在内存中,请使用
std::ostringstream
(来自
标头)。The stream will be in a failure state after you do this (
outFile.fail()
will be true). The text isn't stored anywhere, so no, you can't save it.If you want to store data in memory, use an
std::ostringstream
(from the<sstream>
header) instead.g++ 不会抱怨,因为它是一个编译器并且不运行代码,但运行它可能会导致一些令人讨厌的事情。
同样,如果您尝试取消引用 NULL 指针,g++ 也不会抱怨。
g++ doesn't complain since it is a compiler and doesn't run the code, but running it may cause something nasty.
In the same way, g++ wouldn't complain if you attempt to dereference a
NULL
pointer.当流的操作失败时,流会在内部将错误存储为 位分别代表 eof、fail 和 bad。如果您将其设置为 ios::exceptions()<,流也可能引发异常/a>.
iostream 库设计的一部分似乎是,使用处于错误状态的流将默默地丢弃输出和/或不产生输入,但不会以其他方式提醒用户。这样做的好处是,您可以使用流执行多个操作,然后在最后检查它,确信如果它在中间某个地方失败,它仍然处于失败状态,并且自失败以来没有产生任何结果。
When an action with a stream fails, the stream's stores the error internally as bits representing eof, fail and bad. The stream can also throw an exception if you set it to with ios::exceptions().
Part of the design of the iostream library seems to be that using a stream that's in an error state will silently discard output and/or produce no input, but not otherwise alert the user. The benefit of this is that you can perform multiple operations using the stream and then check it at the end, confident that if it failed somewhere in the middle it's still in a failed state and didn't produce anything since it failed.