To get the meta-information of a file on Linux, we need to use a system call lstat
or stat
.
Stat has been encapsulated in the Golang OS package as a stat function, which is much easier to use than syscall.
This is the OS. The prototype of stat:
func Stat(name string) (FileInfo, error) Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.
Returns an OS. FileInfo, here bread contains meta-information about the file:
type FileInfo interface { Name() string // base name of the file Size() int64 // length in bytes for regular files; system-dependent for others Mode() FileMode // file mode bits ModTime() time.Time // modification time IsDir() bool // abbreviation for Mode().IsDir() Sys() interface{} // underlying data source (can return nil)} A FileInfo describes a file and is returned by Stat and Lstat.
Focus on seeing Sys()
this method, through which we can obtain *syscall.Stat_t
, that is, stat and lstat use and fill in the file meta information struct stat *
.
Os. The information in FileInfo is not complete, so we occasionally need *syscall.Stat_t
to use it to get the information we want, such as when the file was created.
Because the time in the stat_t is all syscall.Timespec
type, we need a little helper function for the visual display of the output content:
func timespecToTime(ts syscall.Timespec) time.Time { return time.Unix(int64(ts.Sec), int64(ts.Nsec))}
Then the next step is to get the code for the Change/create time:
func main() { finfo, _ := os.Stat(filename) // Sys()返回的是interface{},所以需要类型断言,不同平台需要的类型不一样,linux上为*syscall.Stat_t stat_t := finfo.Sys().(*syscall.Stat_t) fmt.Println(stat_t) // atime,ctime,mtime分别是访问时间,创建时间和修改时间,具体参见man 2 stat fmt.Println(timespecToTime(stat_t.Atim)) fmt.Println(timespecToTime(stat_t.Ctim)) fmt.Println(timespecToTime(stat_t.Mtim))}
This is the output effect:
You will find that the modification time is actually ahead of creation time! Don't worry, that is because Atime,ctime, mtime can be artificially modified, some files downloaded from the Internet will also contain meta-information, so this situation, not you cross the:-P
Golang for our development to provide a great convenience, I hope everyone can understand and contact the language.