Power cut before closing ofstream c++

huangapple go评论63阅读模式
英文:

Power cut before closing ofstream c++

问题

在C++中,我正在使用ofstream。如果在调用close()之前所有数据都已写入但在断电之前发生了断电,是否可能导致数据损坏?

请注意,在断电时,ofstream析构函数尚未被调用。

请帮助我理解。

编辑

示例

#include <iostream>
#include <fstream>
int main()
{
    std::ofstream fos("t.bin", std::ios::binary);
    int data = 1;
    fos.write((char*)&data, sizeof(data));
    //---> 在这里执行时发生断电 <---
    fos.close();
    return 0;
}
英文:

I'm using ofstream in c++. It's possible data corruption if all data are written but power cut before calling close() ?

Note that, ofstream destructor has not yet been called at the time of the power cut

Help me to understand please.

Edit

Example

#include &lt;iostream&gt;
#include &lt;fstream&gt;
int main()
{
    std::ofstream fos(&quot;t.bin&quot;, std::ios::binary);
    int data = 1;
    fos.write((char*)&amp;data, sizeof(data));
    //--&gt; power cut when execution is here &lt;--
    fos.close();
    return 0;
}

答案1

得分: 4

有关将数据写入磁盘时涉及的几个层次:

  1. std::ofstream 会将数据保留在内存中,直到调用 flush()close()
  2. 您的操作系统可能会将写入的数据保留在内存中,直到操作系统告诉磁盘写入字节为止。您可以调用 fdatasync()fsync() 来确保至少由操作系统提交。
  3. 最后,您的磁盘可能也有一个小的缓冲区,用于磁盘I/O命令。它最终会开始将数据写入磁盘,但这个机制允许将多个写操作批量处理到相同区域。

即使您做得很正确,仍然存在一个非常小的时间窗口,数据在磁盘缓冲区中等待并尚未写入磁盘。这就是为什么企业级磁盘在断电时仍然可以确保所有排队的写操作都能完成的原因,它们通常配备有小型电池。

英文:

There are several layers involved when writing data to disk:

  1. std::ofstream will keep data in memory until you call flush() or close() it.
  2. Your OS might keep the written data in memory until it gets around to telling the disk to write bytes. You can call fdatasync() or fsync() to ensure at least it is committed by the OS.
  3. Finally, your disk probably also has a small buffer area for disk I/O commands. It will eventually get around to writing it to disk, but this mechanism would allow batching multiple writes to the same area in one operation.

Even if you do everything right, there is still a very tiny window where data is sitting in the disk buffer and not written to disk yet. This is why enterprise-grade disks have a small battery to ensure all queued writes go through even when power is cut.

huangapple
  • 本文由 发表于 2023年7月13日 18:42:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定