fileinfo.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // +build windows
  2. package winio
  3. import (
  4. "os"
  5. "runtime"
  6. "syscall"
  7. "unsafe"
  8. )
  9. //sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx
  10. //sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle
  11. const (
  12. fileBasicInfo = 0
  13. fileIDInfo = 0x12
  14. )
  15. // FileBasicInfo contains file access time and file attributes information.
  16. type FileBasicInfo struct {
  17. CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime
  18. FileAttributes uintptr // includes padding
  19. }
  20. // GetFileBasicInfo retrieves times and attributes for a file.
  21. func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) {
  22. bi := &FileBasicInfo{}
  23. if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
  24. return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
  25. }
  26. runtime.KeepAlive(f)
  27. return bi, nil
  28. }
  29. // SetFileBasicInfo sets times and attributes for a file.
  30. func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error {
  31. if err := setFileInformationByHandle(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
  32. return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err}
  33. }
  34. runtime.KeepAlive(f)
  35. return nil
  36. }
  37. // FileIDInfo contains the volume serial number and file ID for a file. This pair should be
  38. // unique on a system.
  39. type FileIDInfo struct {
  40. VolumeSerialNumber uint64
  41. FileID [16]byte
  42. }
  43. // GetFileID retrieves the unique (volume, file ID) pair for a file.
  44. func GetFileID(f *os.File) (*FileIDInfo, error) {
  45. fileID := &FileIDInfo{}
  46. if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileIDInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil {
  47. return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
  48. }
  49. runtime.KeepAlive(f)
  50. return fileID, nil
  51. }