Skip to content

Commit d133f64

Browse files
authored
examples: add vtail.v, deprecate File.read_bytes_into_newline/1 in favor of File.read_bytes_with_newline/1 (#21182)
1 parent a458ade commit d133f64

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

examples/vtail.v

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import os
2+
import time
3+
4+
if 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+
10+
tfile := os.args[1] or { panic('pass 1 file path as argument') }
11+
mut f := os.open_file(tfile, 'r') or { panic('file ${tfile} does not exist') }
12+
f.seek(0, .end)!
13+
mut read_pos := f.tell()!
14+
mut buf := []u8{len: 10 * 1024}
15+
for {
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+
}

vlib/os/file.c.v

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -450,10 +450,18 @@ pub fn (f &File) read_bytes_at(size int, pos u64) []u8 {
450450
return arr[0..nreadbytes]
451451
}
452452

453-
// read_bytes_into_newline reads from the beginning of the file into the provided buffer.
454-
// Each consecutive call on the same file continues reading where it previously ended.
455-
// A read call is either stopped, if the buffer is full, a newline was read or EOF.
453+
// read_bytes_into_newline reads from the current position of the file into the provided buffer.
454+
@[deprecated: 'use read_bytes_with_newline instead']
455+
@[deprecated_after: '2024-05-04']
456456
pub fn (f &File) read_bytes_into_newline(mut buf []u8) !int {
457+
return f.read_bytes_with_newline(mut buf)
458+
}
459+
460+
// read_bytes_with_newline reads from the current position of the file into the provided buffer.
461+
// Each consecutive call on the same file, continues reading, from where it previously ended.
462+
// A read call is either stopped, if the buffer is full, a newline was read or EOF.
463+
// On EOF, the method returns 0. The methods will also return any IO error encountered.
464+
pub fn (f &File) read_bytes_with_newline(mut buf []u8) !int {
457465
if buf.len == 0 {
458466
return error(@FN + ': `buf.len` == 0')
459467
}

0 commit comments

Comments
 (0)