=Start=
缘由:
之前在Linux下使用过inotify-tools来获知文件的变化情况,在博客里也记录了几篇文章,现在在学习Go 语言,也想了解一下在Go 语言中如何实现类似的功能。
正文:
参考解答:
一个跨平台的简单版实现,来自 this.lau_:
package main import ( "fmt" "os" "time" ) func watchFile(filePath string) error { initialStat, err := os.Stat(filePath) if err != nil { return err } for { stat, err := os.Stat(filePath) if err != nil { return err } if stat.Size() != initialStat.Size() || stat.ModTime() != initialStat.ModTime() { break } time.Sleep(1 * time.Second) } return nil } func main() { doneChan := make(chan bool) go func(doneChan chan bool) { defer func() { doneChan <- true }() err := watchFile("/private/tmp/test") if err != nil { fmt.Println(err) } fmt.Println("File has been changed") }(doneChan) <-doneChan }
使用 fsnotify 包的官方用例:
package main import ( "github.com/fsnotify/fsnotify" "log" ) func ExampleNewWatcher() { watcher, err := fsnotify.NewWatcher() if err != nil { log.Fatal(err) } defer watcher.Close() done := make(chan bool) go func() { for { select { case event, ok := <-watcher.Events: if !ok { return } log.Println("event:", event) if event.Op&fsnotify.Write == fsnotify.Write { log.Println("modified file:", event.Name) } case err, ok := <-watcher.Errors: if !ok { return } log.Println("error:", err) } } }() err = watcher.Add("/private/tmp/foo") if err != nil { log.Fatal(err) } <-done } func main() { ExampleNewWatcher() }
参考链接:
- Go language how detect file changing?
- Cross-platform file system notifications for Go.
https://github.com/fsnotify/fsnotify/blob/master/example_test.go - https://golang.org/pkg/os/#FileInfo
- https://golang.org/pkg/os/#File.Seek
=END=