Skip to content

Commit 539f9f1

Browse files
committed
Add a wrapper for utimes(2)
1 parent d302e8d commit 539f9f1

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

src/sys/time.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
use {NixPath, Result};
2+
use errno::Errno;
13
use std::{cmp, fmt, ops};
2-
use libc::{c_long, time_t, suseconds_t, timespec, timeval};
4+
use libc::{self, c_long, time_t, suseconds_t, timespec, timeval};
35

46
pub trait TimeValLike: Sized {
57
#[inline]
@@ -494,6 +496,19 @@ fn div_rem_64(this: i64, other: i64) -> (i64, i64) {
494496
(this / other, this % other)
495497
}
496498

499+
/// Change the times of the file at `path` to have the access and modification times set to
500+
/// `atime` and `mtime` respectively (see
501+
/// [utimes(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/utimes.html)).
502+
#[inline]
503+
pub fn utimes<P: ?Sized + NixPath>(path: &P, atime: &TimeVal, mtime: &TimeVal) -> Result<()> {
504+
let times: [timeval; 2] = [*atime.as_ref(), *mtime.as_ref()];
505+
let res = try!(path.with_nix_path(|cstr| {
506+
unsafe { libc::utimes(cstr.as_ptr(), &times[0]) }
507+
}));
508+
509+
Errno::result(res).map(drop)
510+
}
511+
497512
#[cfg(test)]
498513
mod test {
499514
use super::{TimeSpec, TimeVal, TimeValLike};

test/sys/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ mod test_select;
2020
mod test_sysinfo;
2121
mod test_termios;
2222
mod test_ioctl;
23+
mod test_time;
2324
mod test_wait;
2425
mod test_uio;
2526

test/sys/test_time.rs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
use nix::sys::time::*;
2+
use std::fs::{self, File};
3+
use std::time::{Duration, UNIX_EPOCH};
4+
use tempfile;
5+
6+
#[test]
7+
fn test_utimes() {
8+
let tempdir = tempfile::tempdir().unwrap();
9+
let file = tempdir.path().join("file");
10+
drop(File::create(&file).unwrap());
11+
12+
let atime = TimeVal::seconds(12345);
13+
let mtime = TimeVal::seconds(678);
14+
utimes(&file, &atime, &mtime).unwrap();
15+
16+
let attr = fs::symlink_metadata(&file).unwrap();
17+
assert_eq!(
18+
Duration::new(12345, 0),
19+
attr.accessed().unwrap().duration_since(UNIX_EPOCH).unwrap());
20+
assert_eq!(
21+
Duration::new(678, 0),
22+
attr.modified().unwrap().duration_since(UNIX_EPOCH).unwrap());
23+
}

0 commit comments

Comments
 (0)