Browse Source

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

main
xiaoqidun 6 months ago
parent
commit
c7331dc186
  1. 3
      .gitignore
  2. 2
      README.md
  3. 3
      go.mod
  4. 12
      setft.go
  5. 16
      setft_test.go
  6. 26
      setft_windows.go

3
.gitignore

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

2
README.md

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

3
go.mod

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

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

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

26
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)
}
Loading…
Cancel
Save