在文件系统路径处自动创建文件
即使路径中的中间元素不存在,原子在路径中创建文件的惯用方法是什么?
例如,给定一个如下所示的目录,
$ tree one
one
├── two
└── three
我想以原子方式将字符串写入路径“一/四/五/六”处的文件。
在这种情况下,我所说的“原子”是指——如果写入失败,我不希望路径 one/four
存在。如果写入成功,我希望整个路径 one/four/ Five/six
有效并具有我写入的字符串。我不关心写入后的持久性保证,所以我不关心“如果写入成功,那么文件必须存在于给定路径,即使在发生电源故障”。
寻找标准 C++ 中的实现(因此使用 std::filesystem
或 ofstream
的任何内容都很好,但不是必需的,如果必须的话,我可以使用常规 POSIX API )。
What is the idiomatic way to atomically create a file at a path, even if intermediate elements in the path do not exist?
For example, given a directory that looks like this
$ tree one
one
├── two
└── three
I want to write a string to the file at path "one/four/five/six" atomically.
In this context, by "atomic" I mean -- if the write fails, I don't want the path one/four
to exist. If the write succeeds, I want the whole path one/four/five/six
to be valid and have the string that I wrote to it. I do not care about a durability guarantee after the write, so I do not care about "if the write succeeds, then the file must be present at the given path even in the event of a power failure".
Looking for an implementation in standard C++ (so anything using std::filesystem
or ofstream
would be nice, but not required, I can use the regular POSIX API if I have to).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论