feat(初始项目): 初始项目

This commit is contained in:
xiaoqidun 2021-03-26 19:21:06 +08:00
parent ef16e03909
commit c7331dc186
6 changed files with 62 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.idea/
.vscode/
.devcontainer/

View File

@ -1 +1,3 @@
# setft
Golang SetFileTime修改文件的访问时间、创建时间、修改时间。

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module github.com/xiaoqidun/setft
go 1.16

12
setft.go Normal file
View File

@ -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)
}

16
setft_test.go Normal file
View File

@ -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)
}
}

26
setft_windows.go Normal file
View File

@ -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)
}