Skip to content

Commit 1afa2a1

Browse files
bradfitzrsc
authored andcommitted
os: add Chtimes function
R=rsc, r CC=golang-dev https://golang.org/cl/1103041
1 parent cbc01a3 commit 1afa2a1

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/pkg/os/file.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,3 +407,19 @@ func (f *File) Truncate(size int64) Error {
407407
}
408408
return nil
409409
}
410+
411+
// Chtimes changes the access and modification times of the named
412+
// file, similar to the Unix utime() or utimes() functions.
413+
//
414+
// The argument times are in nanoseconds, although the underlying
415+
// filesystem may truncate or round the values to a more
416+
// coarse time unit.
417+
func Chtimes(name string, atime_ns int64, mtime_ns int64) Error {
418+
var utimes [2]syscall.Timeval
419+
utimes[0] = syscall.NsecToTimeval(atime_ns)
420+
utimes[1] = syscall.NsecToTimeval(mtime_ns)
421+
if e := syscall.Utimes(name, &utimes); e != 0 {
422+
return &PathError{"chtimes", name, Errno(e)}
423+
}
424+
return nil
425+
}

src/pkg/os/os_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,48 @@ func TestTruncate(t *testing.T) {
483483
Remove(Path)
484484
}
485485

486+
func TestChtimes(t *testing.T) {
487+
MkdirAll("_obj", 0777)
488+
const Path = "_obj/_TestChtimes_"
489+
fd, err := Open(Path, O_WRONLY|O_CREAT, 0666)
490+
if err != nil {
491+
t.Fatalf("create %s: %s", Path, err)
492+
}
493+
fd.Write([]byte("hello, world\n"))
494+
fd.Close()
495+
496+
preStat, err := Stat(Path)
497+
if err != nil {
498+
t.Fatalf("Stat %s: %s", Path, err)
499+
}
500+
501+
// Move access and modification time back a second
502+
const OneSecond = 1e9 // in nanoseconds
503+
err = Chtimes(Path, preStat.Atime_ns-OneSecond, preStat.Mtime_ns-OneSecond)
504+
if err != nil {
505+
t.Fatalf("Chtimes %s: %s", Path, err)
506+
}
507+
508+
postStat, err := Stat(Path)
509+
if err != nil {
510+
t.Fatalf("second Stat %s: %s", Path, err)
511+
}
512+
513+
if postStat.Atime_ns >= preStat.Atime_ns {
514+
t.Errorf("Atime_ns didn't go backwards; was=%d, after=%d",
515+
preStat.Atime_ns,
516+
postStat.Atime_ns)
517+
}
518+
519+
if postStat.Mtime_ns >= preStat.Mtime_ns {
520+
t.Errorf("Mtime_ns didn't go backwards; was=%d, after=%d",
521+
preStat.Mtime_ns,
522+
postStat.Mtime_ns)
523+
}
524+
525+
Remove(Path)
526+
}
527+
486528
func TestChdirAndGetwd(t *testing.T) {
487529
fd, err := Open(".", O_RDONLY, 0)
488530
if err != nil {

0 commit comments

Comments
 (0)