v / examples / vtail.v
27 lines · 25 sloc · 779 bytes · d133f64c86577bc743ad24747d266a17af8f1568
Raw
1import os
2import time
3
4if os.args.len == 1 {
5 eprintln('A small `tail -f file` like program, written in V.')
6 eprintln('Usage: `v run examples/vtail.v your_long_file.log`')
7 exit(0)
8}
9
10tfile := os.args[1] or { panic('pass 1 file path as argument') }
11mut f := os.open_file(tfile, 'r') or { panic('file ${tfile} does not exist') }
12f.seek(0, .end)!
13mut read_pos := f.tell()!
14mut buf := []u8{len: 10 * 1024}
15for {
16 bytes := f.read_bytes_with_newline(mut buf)!
17 if bytes == 0 && f.eof() {
18 // The end of the file has been reached, so wait a bit, and retry from the same position:
19 f.close()
20 time.sleep(500 * time.millisecond)
21 f = os.open_file(tfile, 'r')!
22 f.seek(read_pos, .start)!
23 continue
24 }
25 read_pos += bytes
26 print(unsafe { (&u8(buf.data)).vstring_with_len(bytes) })
27}
28