在linux上想擷取檔案的元資訊,我們需要使用系統調用 lstat stat
或者
。
在golang的os包裡已經把stat封裝成了Stat函數,使用它比使用syscall要友善不少。
這是os.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.
傳回一個os.FileInfo,這裡面包含有檔案的元資訊:
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.
重點看到
Sys()
這個方法,通過它我們可以獲得
*syscall.Stat_t
,也就是stat和lstat使用并填入檔案元資訊的
struct stat *
os.FileInfo裡的資訊并不完整,是以我們偶爾需要使用
*syscall.Stat_t
來擷取自己想要的資訊,比如檔案的建立時間。
因為Stat_t裡的時間都是
syscall.Timespec
類型,是以我們為了輸出内容的直覺展示,需要一點helper function:
func timespecToTime(ts syscall.Timespec) time.Time {
return time.Unix(int64(ts.Sec), int64(ts.Nsec))
}
然後接下來就是擷取修改/建立時間的代碼:
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))
}
這是輸出效果:

你會發現修改時間居然提前于建立時間!别擔心,那是因為atime,ctime, mtime都可以人為修改,一些從網上下載下傳回來的檔案也會包含元資訊,是以才會出現這種情況,并不是你穿越了:-P
golang為我們的開發提供了極大的便利,希望大家都能了解和接觸這門語言。