可以向未打开的 C++ 写入数据; ofstream 到文件?

发布于 2024-11-14 06:17:34 字数 194 浏览 1 评论 0原文

对于未打开我的意思是:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南汐寒笙箫 2024-11-21 06:17:34

执行此操作后,流将处于失败状态(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.

暮倦 2024-11-21 06:17:34

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.

戈亓 2024-11-21 06:17:34

当流的操作失败时,流会在内部将错误存储为 分别代表 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文