我需要将文件从给定的源复制到给定的目标,不仅仅是文件内容,还有它的元数据。特别是,我需要确保副本与源具有相同的修改时间。
要复制文件,我使用函数 std::fs::copy
.它的文档没有指定是否复制了元数据,并且在极少数情况下它无法复制文件元数据。
以下代码:
fs::copy(source, dest)?;
debug_assert_eq!(
fs::metadata(source)?.modified()?,
fs::metadata(dest)?.modified()?
);
有时 panic :
thread 'main' panicked at 'assertion failed: `(left == right)`
left: `SystemTime { tv_sec: 1556721917, tv_nsec: 270615000 }`,
right: `SystemTime { tv_sec: 1556721917, tv_nsec: 0 }`',
当此操作失败时,tv_nsec
字段始终设置为 0。
这是 std::fs::copy
的错误吗?我怎样才能复制文件元数据?
最佳答案
您必须调用 sync_all()
.
Attempts to sync all OS-internal metadata to disk.
This function will attempt to ensure that all in-memory data reaches the filesystem before returning.
This can be used to handle errors that would otherwise only be caught when the File is closed. Dropping a file will ignore errors in synchronizing this in-memory data.
关于file - 如何在 Linux 和 Windows 上从 std::fs 支持的任何文件系统复制文件元数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56827719/