基本上我有以下工作流程(通过控制台应用程序):
- 读取二进制文件 (
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));
}