Function std::fs::set_file_times can't set only accessed or modified time

We sometimes want to change only accessed time (or modified time) of a file.
However, function std::fs::set_file_times requires both accessed and modified time.

I think the signature of set_files_times should be something like:

pub fn set_file_times<P: AsRef<Path>>(path: P, accessed: Option<u64>, modified: Option<u64>) -> Result<()>;

I know it is waiting for the time when the standard library gains a type to represent a moment.
I just want to know if there is a plan to consider the case above.

Thanks.

3 Likes

SetFileTime on Windows allows you to use the equivalent of Option for each parameter (null pointers), so I see no reason why the Rust API can't expose something like this.

While this is possible on Windows, as far as I can tell the unix equivalent (utime) requires both at the same time.

This would be nice to have as a function in std::os, because of the limitation in unix I don't think it belongs in cross-platform API. Even though it would be possible to grab the time, then copy what time was specified as None, I don't think that behavior would be atomic and that would be a bit counter-intuitive for an API like this.

I realise this is uhm, 4 years too late, but it is possible on unix - don't use the obsolete utimes call; instead utimensat(2) - Linux man page (and futimesnsat) with UTIME_OMIT.

Is this something that could be adjusted in a new edition of rust?

If we still had std::fs::set_file_times, then it could be! But at the moment I don't think there are currently any functions in std for modifying file times, only read-only APIs.

The original functionality, set_file_times, was unstable when this post was made. It was removed shortly afterwards due to it operating on u64 values rather than a proper time type, and no replacement was added. Today, we just have read-only access to file times .

The utime crate provides the same functionality, though. Maybe a PR to that crate could be made for access-time only or modify-time only modifications?

The filetime crate has similarly inherited the functionality, and I put forward a PR to it to do fd / handle based modifications using the relevant platform specific API's which have the access/modify split already - another contributor had already put forward a patch for the path based version. Thats all released now.

1 Like