如何原子性地替换一个文件?

huangapple go评论100阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月7日 18:13:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75660604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定