How to copy file metadata on Linux and Windows from and to any filesystem that is supported by std::fs?

Viewed 478

I need to copy a file from a given source to a given destination, not just the file content, but its metadata as well. In particular, I need to be sure that the copy will have the same modified time as the source.

To copy a file I use the function std::fs::copy. Its documentation doesn't specify if the metadata is copied or not, and it fails in rare cases in copying the file metadata.

The following code:

fs::copy(source, dest)?;
debug_assert_eq!(
    fs::metadata(source)?.modified()?,
    fs::metadata(dest)?.modified()?
);

sometimes panics:

thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `SystemTime { tv_sec: 1556721917, tv_nsec: 270615000 }`,
 right: `SystemTime { tv_sec: 1556721917, tv_nsec: 0 }`',

When this fails the tv_nsec field is always set to 0. Is this a bug of std::fs::copy? How can I copy the file metadata too?

1 Answers

You must call 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.

Related