在两个不同进程的附加模式中使用ofstream

时间:2013-07-15 23:31:01

标签: c++ append ofstream

C ++程序P1使用ios :: app在不存在的文件上创建流。然后它写了几个字符串(其中没有“\ n”)但不使用endl(因此缓冲区不会被刷新)。然后等待2秒钟并关闭文件。

程序P2与P1相同,只是它没有等待。我期待P1覆盖文件中写入的任何P2,因为它的缓冲区在2秒后刷新,但事实并非如此。 P2的输出正确显示,然后在文件中输出P1。

经过许多这样的实验,在我看来,“app”模式在每次写入后刷新缓冲区(即使没有使用endl)。我想知道其他人是否面临类似的情况,如果我的结论是正确的。谢谢你提前。

2 个答案:

答案 0 :(得分:0)

您在这里依赖于未定义的行为 - 如果您不使用std :: endl,则无法保证它不会刷新。不依赖于未定义或假定的行为 - 仅依赖于明确指定的行为。

详细说明:

1.3.24                                                                                    [defns.undefined]
undefined behavior
behavior for which this International Standard imposes no requirements
[ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of
behavior or when a program uses an erroneous construct or erroneous data. Permissible undefined behavior
ranges from ignoring the situation completely with unpredictable results, to behaving during translation or
program execution in a documented manner characteristic of the environment (with or without the issuance of
a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
Many erroneous program constructs do not engender undefined behavior; they are required to be diagnosed.
— end note ]

c ++ 11或c ++ 03对user2585330所依赖的行为没有要求。

答案 1 :(得分:0)

简短回答:不,你不能依赖这种行为。

在一段时间的类似问题中,我写了一些代码来完成这一点,它确实不起作用(不一定是进程覆盖了其他数据 - 我没有看到那个特定的行为,但那不是我在寻找什么 - 在这种情况下的问题是,如果数据保证从一个进程和另一个进程“完整” - 这显然也是你关注的问题之一,即使你没有提出这个问题)。您将从一个进程中获得数据的“块”,并混合来自另一个进程的“块”数据。究竟它们如何混合在一起取决于什么平台,系统负载是什么,一周中的哪一天(模糊相关,可能不是真的),以及可能还有十几个其他因素。

从技术上讲,C ++标准不知道/关心多个进程,就语言而言,只有一个进程 - 想象一下这个语言是在旧的DOS系统上工作,只有一个进程在任何给定的时间运行。因此,如果您有多个进程使用相同的文件,标准没有说明会发生什么。