Skip to content

std.reader

API summary (generated from the Beans source by npm run coverage): 1 type · 1 constructor · 3 instance methods.

std.reader gives you a Reader that reads a File one line at a time. It buffers behind the scenes so you are not making a syscall per line. Read the source at stdlib/std/reader/reader.b.

import std.reader

You build one with new, moving in an open file. The reader owns that handle:

pub class Reader
new Reader(move file: File)
pub fn file_position() -> int
pub fn close() -> Result<bool>
pub fn read_line() -> Result<Option<string>>
  • read_line returns ok(some(line)) for each line, with the trailing newline removed. At end of file it returns ok(none). If the read fails, you get an error.
  • file_position reports the underlying file cursor. Positional reads leave it unchanged.
  • close closes the owned file. Bytes already buffered can still be returned; the next refill reports the closed handle.

The reader keeps its own offset and reads with pread, so it never moves the underlying file’s cursor. You can read the same file another way at the same time without the two interfering.

import std.io
import std.reader
fn main() {
let file: File = File.open("log.txt", "r").expect("open")
let r: reader.Reader = new reader.Reader(move file)
for true {
let line: Option<string> = r.read_line().expect("read")
match line {
some(text) => io.println(text),
none => { break },
}
}
r.close().expect("close")
}
  • Files and mapping, the File type you open and pass in.
  • std.fs, read a whole file at once when you do not need it line by line.