diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77c6356 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.idea/ +.vscode/ +.devcontainer/ diff --git a/README.md b/README.md index 9ccbdc0..3d24a37 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ # setft +Golang SetFileTime,修改文件的访问时间、创建时间、修改时间。 + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f2eb45c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/xiaoqidun/setft + +go 1.16 diff --git a/setft.go b/setft.go new file mode 100644 index 0000000..2c17e67 --- /dev/null +++ b/setft.go @@ -0,0 +1,12 @@ +// +build !windows + +package setft + +import ( + "os" + "time" +) + +func SetFileTime(path string, atime, ctime, mtime time.Time) (err error) { + return os.Chtimes(path, atime, mtime) +} diff --git a/setft_test.go b/setft_test.go new file mode 100644 index 0000000..1f76482 --- /dev/null +++ b/setft_test.go @@ -0,0 +1,16 @@ +package setft + +import ( + "testing" + "time" +) + +func TestSetFileTime(t *testing.T) { + layout := "2006-01-02 15:04:05" + atime, _ := time.ParseInLocation(layout, "2021-01-01 00:00:00", time.Local) + ctime, _ := time.ParseInLocation(layout, "2021-01-01 00:00:00", time.Local) + mtime, _ := time.ParseInLocation(layout, "2021-01-01 00:00:00", time.Local) + if err := SetFileTime("setft_test.go", atime, ctime, mtime); err != nil { + t.Fatal(err) + } +} diff --git a/setft_windows.go b/setft_windows.go new file mode 100644 index 0000000..b3850bb --- /dev/null +++ b/setft_windows.go @@ -0,0 +1,26 @@ +package setft + +import ( + "syscall" + "time" +) + +func SetFileTime(path string, atime, ctime, mtime time.Time) (err error) { + path, err = syscall.FullPath(path) + if err != nil { + return + } + pathPtr, err := syscall.UTF16PtrFromString(path) + if err != nil { + return + } + handle, err := syscall.CreateFile(pathPtr, syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return + } + defer syscall.Close(handle) + a := syscall.NsecToFiletime(syscall.TimespecToNsec(syscall.NsecToTimespec(atime.UnixNano()))) + c := syscall.NsecToFiletime(syscall.TimespecToNsec(syscall.NsecToTimespec(ctime.UnixNano()))) + m := syscall.NsecToFiletime(syscall.TimespecToNsec(syscall.NsecToTimespec(mtime.UnixNano()))) + return syscall.SetFileTime(handle, &c, &a, &m) +}