diff --git a/examples/vtail.v b/examples/vtail.v new file mode 100644 index 0000000000..eb6ab15c93 --- /dev/null +++ b/examples/vtail.v @@ -0,0 +1,27 @@ +import os +import time + +if os.args.len == 1 { + eprintln('A small `tail -f file` like program, written in V.') + eprintln('Usage: `v run examples/vtail.v your_long_file.log`') + exit(0) +} + +tfile := os.args[1] or { panic('pass 1 file path as argument') } +mut f := os.open_file(tfile, 'r') or { panic('file ${tfile} does not exist') } +f.seek(0, .end)! +mut read_pos := f.tell()! +mut buf := []u8{len: 10 * 1024} +for { + bytes := f.read_bytes_with_newline(mut buf)! + if bytes == 0 && f.eof() { + // The end of the file has been reached, so wait a bit, and retry from the same position: + f.close() + time.sleep(500 * time.millisecond) + f = os.open_file(tfile, 'r')! + f.seek(read_pos, .start)! + continue + } + read_pos += bytes + print(unsafe { (&u8(buf.data)).vstring_with_len(bytes) }) +} diff --git a/vlib/os/file.c.v b/vlib/os/file.c.v index 66b0105941..4b3112364d 100644 --- a/vlib/os/file.c.v +++ b/vlib/os/file.c.v @@ -450,10 +450,18 @@ pub fn (f &File) read_bytes_at(size int, pos u64) []u8 { return arr[0..nreadbytes] } -// read_bytes_into_newline reads from the beginning of the file into the provided buffer. -// Each consecutive call on the same file continues reading where it previously ended. -// A read call is either stopped, if the buffer is full, a newline was read or EOF. +// read_bytes_into_newline reads from the current position of the file into the provided buffer. +@[deprecated: 'use read_bytes_with_newline instead'] +@[deprecated_after: '2024-05-04'] pub fn (f &File) read_bytes_into_newline(mut buf []u8) !int { + return f.read_bytes_with_newline(mut buf) +} + +// read_bytes_with_newline reads from the current position of the file into the provided buffer. +// Each consecutive call on the same file, continues reading, from where it previously ended. +// A read call is either stopped, if the buffer is full, a newline was read or EOF. +// On EOF, the method returns 0. The methods will also return any IO error encountered. +pub fn (f &File) read_bytes_with_newline(mut buf []u8) !int { if buf.len == 0 { return error(@FN + ': `buf.len` == 0') }