Home >Backend Development >Golang >How to Efficiently Read the Last Lines from a Large File in Go Every 10 Seconds?
Challenge: Reading the last two lines of a large log file without loading the entire file into memory, repeating this process every 10 seconds.
Stat Function: To avoid loading the entire file into memory, the file's length can be obtained using the Stat() function of the os package. This provides the file size in bytes.
Seeking or Reading Forward:
Consider the example provided in your question:
Code Snippet:
package main import ( "fmt" "os" "time" ) const MYFILE = "logfile.log" func main() { c := time.Tick(10 * time.Second) for _ = range c { readFile(MYFILE) } } func readFile(fname string) { file, err := os.Open(fname) if err != nil { panic(err) } defer file.Close() buf := make([]byte, 62) stat, statErr := file.Stat() if statErr != nil { panic(statErr) } start := stat.Size() - 62 _, err = file.ReadAt(buf, start) if err == nil { fmt.Printf("%s\n", buf) } }
In this example:
The above is the detailed content of How to Efficiently Read the Last Lines from a Large File in Go Every 10 Seconds?. For more information, please follow other related articles on the PHP Chinese website!