← All Exercises

Read the Last N Lines of a File

advancedgo~30min

Background

Log viewers and CLI tools tail huge files; reading backward in chunks avoids scanning gigabytes just to show the final lines.

Problem

Implement tailFile(path string, n int) ([]string, error). Return the last n lines in order without line terminators. Handle n=0, empty files, trailing newlines, and files without a final newline; reject negative n.

Input

A file path and a non-negative line count.

Output

The last n lines as a slice in original order, or an error when the file cannot be read.

Sample tests

Sample 1

Input: file contains "alpha\nbeta\ngamma\n", n = 2
Expected: beta, gamma

Sample 2

Input: same file, n = 10
Expected: alpha, beta, gamma

Sample 3

Input: same file, n = 0
Expected: []

Your solution

Learning objective

Use io.ReaderAt and backward scanning for memory-bounded tail operations with correct newline handling.