英文:
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 <iostream>
#include <fstream>
int main()
{
std::ofstream fos("t.bin", std::ios::binary);
int data = 1;
fos.write((char*)&data, sizeof(data));
//--> power cut when execution is here <--
fos.close();
return 0;
}
答案1
得分: 4
有关将数据写入磁盘时涉及的几个层次:
std::ofstream
会将数据保留在内存中,直到调用flush()
或close()
。- 您的操作系统可能会将写入的数据保留在内存中,直到操作系统告诉磁盘写入字节为止。您可以调用
fdatasync()
或fsync()
来确保至少由操作系统提交。 - 最后,您的磁盘可能也有一个小的缓冲区,用于磁盘I/O命令。它最终会开始将数据写入磁盘,但这个机制允许将多个写操作批量处理到相同区域。
即使您做得很正确,仍然存在一个非常小的时间窗口,数据在磁盘缓冲区中等待并尚未写入磁盘。这就是为什么企业级磁盘在断电时仍然可以确保所有排队的写操作都能完成的原因,它们通常配备有小型电池。
英文:
There are several layers involved when writing data to disk:
std::ofstream
will keep data in memory until you callflush()
orclose()
it.- Your OS might keep the written data in memory until it gets around to telling the disk to write bytes. You can call
fdatasync()
orfsync()
to ensure at least it is committed by the OS. - 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论