Skip to content

Commit

Permalink
examples: add vtail.v, deprecate File.read_bytes_into_newline/1 in fa…
Browse files Browse the repository at this point in the history
…vor of File.read_bytes_with_newline/1 (#21182)
  • Loading branch information
spytheman committed Apr 4, 2024
1 parent a458ade commit d133f64
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
27 changes: 27 additions & 0 deletions examples/vtail.v
Original file line number Diff line number Diff line change
@@ -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) })
}
14 changes: 11 additions & 3 deletions vlib/os/file.c.v
Original file line number Diff line number Diff line change
Expand Up @@ -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')
}
Expand Down

0 comments on commit d133f64

Please sign in to comment.