Got it! For large files, reading the entire file into memory is inefficient. Instead, we can read the file from the end and collect the last N lines without loading the whole file.
Here’s a Go implementation that efficiently reads the last 3 lines from large files by reading backwards in chunks:
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"path/filepath"
)
func readLastLines(filePath string, numLines int) error {
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("error opening %s: %w", filePath, err)
}
defer file.Close()
const chunkSize = 1024
fileInfo, err := file.Stat()
if err != nil {
return fmt.Errorf("error stating file %s: %w", filePath, err)
}
var (
fileSize = fileInfo.Size()
offset = fileSize
lines []string
leftover []byte
lineCount = 0
)
for offset > 0 && lineCount < numLines {
// Calculate how much to read
readSize := chunkSize
if offset < int64(readSize) {
readSize = int(offset)
}
offset -= int64(readSize)
// Read chunk from file
buf := make([]byte, readSize)
_, err := file.ReadAt(buf, offset)
if err != nil && err != io.EOF {
return fmt.Errorf("error reading file %s: %w", filePath, err)
}
// Prepend leftover from previous chunk
buf = append(buf, leftover...)
// Split lines by newline
linesInChunk := bytes.Split(buf, []byte{'\n'})
// The first element might be partial line, save it for next iteration
leftover = linesInChunk[0]
// Process lines in reverse order (except the first partial line)
for i := len(linesInChunk) - 1; i > 0 && lineCount < numLines; i-- {
line := string(linesInChunk[i])
lines = append([]string{line}, lines...) // prepend line
lineCount++
}
}
// If we still need lines and leftover is not empty, add it
if lineCount < numLines && len(leftover) > 0 {
lines = append([]string{string(leftover)}, lines...)
}
fmt.Printf("Last %d lines from %s:\n", numLines, filePath)
for _, line := range lines {
fmt.Println(line)
}
fmt.Println()
return nil
}
func main() {
drives := []string{"N", "O", "P", "Q"}
for _, drive := range drives {
path := filepath.Join(drive+":", "weightreader", "weightreader.log")
if err := readLastLines(path, 3); err != nil {
fmt.Println(err)
}
}
fmt.Println("Press Enter to continue...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
How this works:
- It reads the file in chunks starting from the end.
- Splits each chunk by newline and collects lines in reverse order.
- Stops once it has collected the requested number of lines.
- Handles partial lines that span chunks.
- Efficient for large files because it never reads the entire file into memory.
Let me know if you want me to explain any part or improve it further!