英文:
How to atomically replace a file?
问题
if Path::new(&filename).exists() {
remove_file(&filename)?;
debug!("旧输出文件已删除:{}", filename);
}
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.create(true)
.open(&filename)?;
debug!("输出文件已打开并截断:{}", filename);
英文:
I'm currently using:
if Path::new(&filename).exists() {
remove_file(&filename)?;
debug!("old output file deleted: {filename}");
}
let mut file = OpenOptions::new()
.create_new(true)
.append(true)
.open(&filename)?;
debug!("output file opened: {filename}");
I'm aware that this is a possible race condition.
How can I open and truncate a file in one operation?
答案1
得分: 2
在POSIX API中,creat()
系统调用 是使用 O_CREAT|O_WRONLY|O_TRUNC
选项的 open()
的快捷方式。
在Rust文档的 std::fs::OpenOptions
中,我们找到了关于 truncate()
的示例。还请注意,std::fs::File::create()
等同于 creat()
系统调用。
以这种方式打开文件将在文件不存在时创建它,或者在文件已存在时将其截断;所有随后的写入调用将发生在最初为空的文件中。
英文:
In the POSIX API, the creat()
system call is a shortcut for open()
with O_CREAT|O_WRONLY|O_TRUNC
.
In the Rust documentation for std::fs::OpenOptions
we find an example for truncate()
.
Note also that std::fs::File::create()
is equivalent to the creat()
system-call.
Opening a file this way will create it if it does not already exist, or truncate it if it already exists; all the subsequent write calls will take place in a file which is originally empty.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论