file - 如何在 Linux 和 Windows 上从 std::fs 支持的任何文件系统复制文件元数据?

标签 file rust copy metadata

我需要将文件从给定的源复制到给定的目标,不仅仅是文件内容,还有它的元数据。特别是,我需要确保副本与源具有相同的修改时间。

要复制文件,我使用函数 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/

相关文章:

linux - 逐行比较 2 个文件的脚本

java - java中的文件重复

concurrency - 将输出 `io::Write` 传递给使用线程的函数的最佳方法是什么?

Rust:使用部分移动的值

rust - 这两种为 Rust channel 克隆发送者的方式有什么区别?

java - 对象数组的深拷贝

android - 将数据库从 Assets 复制到数据库文件夹

c# - FileSystemWatcher 有一个奇怪的行为

excel - Microsoft Excel 以日期格式复制和粘贴

c - 如何从 C 语言的文件中逐行读取每行两个字符串