Capy-Bearer Documentation

file_tail

lib call

Capy

function file_tail(path : string, lines : s64, opt : any = {}) any

Description

file_tail returns the last lines of a file, as tail -n does. It reads the file backwards from its end in 64 KiB blocks and stops when it has the lines, so the time depends on the size of the result, not of the file. Use it to show the end of a log. file_get_contents would read the whole log into memory.

The final newline of the file ends the last line. A file without a final newline returns its last line without one. When the file has fewer lines, the result is the whole file. lines: 0 returns "".

When the lines are longer than max_bytes, the result is the last max_bytes bytes, so its first line can start in the middle.

file_tail holds a shared lock while it reads, like file_get_contents. It waits at most the lock timeout for a writer. A missing file, a path outside the readable roots, or a lock timeout returns a failure.

To follow a file as it grows, run tail -F in a service: port_spawn(["tail", "-F", path]) delivers each new chunk as a SERVICE:DATA event.

Parameters

path : path of the file to read

lines : number of lines to return from the end of the file

opt : max_bytes, the largest result in bytes, 1048576 by default

Return Values

{ok: true, value: ...} on success, or {ok: false, error: "..."} on failure. The value field contains the last lines lines, each with its newline.

Errors

A negative lines, an unknown option key, or a max_bytes outside 1 through 67108864 is a hard error.

Example

Capy

var path := file_temp()
file_put_contents(path, "first\nsecond\nthird\n")
try text := file_tail(path, 2)
{
	print(text)
}
else
{
	print(text.error, "\n")
}

Output

second
third