gpt4 book ai didi

c++ - std::ofstream 被销毁后文件是否可以立即读取?

转载 作者:行者123 更新时间:2023-11-30 01:58:34 25 4
gpt4 key购买 nike

基本上我有以下工作流程(通过控制台应用程序):

  • 读取二进制文件(std::ifstream::read)
  • 对读取的数据做一些事情
  • 写回同一个文件(std::ofstream::write),覆盖什么以前在那里。

现在,如果我通过 shell 脚本(始终使用同一个文件)运行整个控制台程序 1000 次,是否可以安全地假设读取操作不会与先前运行的试图写入文件的程序发生冲突?或者我需要在两次执行之间等待(多长时间???)?我能否可靠地确定文件是否准备就绪?

我知道这不是最好的设计,只是想知道它是否会可靠地工作(试图快速收集一些统计数据 - 输入不同,但输出文件始终相同 - 需要读取,需要处理信息, 然后它需要更新(此时只需覆盖它))。

编辑:

看起来输出错误的问题与基于答案的操作系统无关,我做的读/写看起来像:

//read
std::ifstream input(fname,std::ios_base::binary);
while(input)
{
unsigned value;
input.read(reinterpret_cast<char*>(&value),sizeof(unsigned));
....
}
input.close();
...

//write
std::ofstream output(fname,std::ios_base::binary);
for(std::map<unsigned,unsigned>::const_iterator iter =originalMap.begin();iter != originalMap.end();++iter)
{
unsigned temp = iter->first;
output.write(reinterpret_cast<char*>(&temp),sizeof(unsigned));
temp = iter->second;
output.write(reinterpret_cast<char*>(&temp),sizeof(unsigned));
}

最佳答案

They are running sequentially, essentially, shell script runs same console app in a loop...

那么,在任何“正常”的操作系统上,应该都没有问题。

当应用程序终止时,流被销毁,因此所有可能由 C/C++ 流保存在缓存中的数据都写入底层操作系统流中,然后关闭。

操作系统是否做更多的缓存是无关紧要的——操作系统做的缓存对应用程序是透明的,因此,就应用程序而言,数据现在写入文件中。如果它实际上写在磁盘上在这里无关紧要 - 从文件读取的应用程序无论如何都会看到其中的数据。

如果您考虑一下,如果没有这样的保证,在计算机上可靠地完成任何工作都会很复杂! :)


更新:

std::ofstream output(fname,std::ios_base::binary);

您应该在写入之前截断输出文件,否则,如果输入文件比输出文件长,旧数据仍将滞留在文件末尾:

std::ofstream output(fname,std::ios_base::binary | std::ios_base::trunc);

关于c++ - std::ofstream 被销毁后文件是否可以立即读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com