In Go, you can watch for file changes using the `fsnotify` package. This package provides a simple way to monitor file system events, such as modifications, creations, deletions, and renaming of files and directories. Below is a code example demonstrating how to use `fsnotify` to watch for changes in a specific file or directory.
package main
import (
"fmt"
"log"
"github.com/fsnotify/fsnotify"
)
func main() {
// Create a new file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
// Start listening for events
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
fmt.Println("event:", event)
if event.Op&fsnotify.Write == fsnotify.Write {
fmt.Println("modified file:", event.Name)
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
// Add a specific file or directory to watch
err = watcher.Add("/path/to/your/file/or/directory")
if err != nil {
log.Fatal(err)
}
// Block forever
<-make(chan struct{})
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?