Skip to content

Os.stdin ​

ant
func Os.stdin(): File.Handle

Os.stdin returns the program's standard input, open for reading only. A read takes what is there, which may be more than the line it returns; what it took stays the program's, so a script that hands the rest of its input to a child reads it and gives it as input.

Details ​

  • Os.stdin returns a File.Handle open for reading only, so a write to it is Err, even when it is a terminal. Every File read works on it: File.readLine, File.readAll, File.readChunk, File.pipe.
  • At the end of the input, readLine and readChunk give null and readAll gives "". In the REPL, standard input belongs to the REPL: Os.stdin() is at end of file, and so is the standard input of a child the REPL starts with Cmd.run.
  • File.close on standard input does nothing and is Ok, so a function may close any handle it reads without asking which one it is.
  • A read takes what is there, which may be more than the line it returns, and keeps it for the program's next read. A child started with Cmd.run gets only input that arrives after that, so to hand the rest of the input to a child, read it and pass it as input to Cmd.read. A read whose ctx ends returns Err, but the stream itself cannot be interrupted: what arrives afterwards is kept for the program's next read, not given to a child.

Basic examples ​

Read all of standard input with File.readAll:

ant
let text = try File.readAll(Os.stdin())
println("${text.lines().length()} lines")
text
3 lines

Read it a line at a time with File.readLine, which gives null at the end:

ant
let input = Os.stdin()
while true {
  let name = try input.readLine() ?? break
  println("Hello, ${name}")
}
text
Hello, Ann
Hello, Bob

Scope ​

Empty input is at its end from the first read:

ant
let input = Os.stdin()
println(input.readLine())
println(input.readAll())
text
Ok{ value: null }
Ok{ value: "" }

The reads of standard input share one buffer, so a program can read a header line and then the rest in one piece:

ant
let input = Os.stdin()
let header = try input.readLine() ?? ""
println(header.split(","))
print(try input.readAll())
text
["name", "score"]
Ann,9
Bob,7

File.readChunk reads the input as bytes, at most max at a time:

ant
let input = Os.stdin()
while true {
  let chunk = try input.readChunk(2) ?? break
  println(chunk)
}
text
Bytes(68 69)
Bytes(21 0a)

Applications ​

Copy standard input to standard output, as cat does, with File.pipe:

ant
try File.pipe(Os.stdin(), Os.stdout())
text
first
second

Ask a question and read the answer. Standard output is not buffered, so the prompt shows before the read waits:

ant
print("Name: ")
let name = try Os.stdin().readLine() ?? "stranger"
println("Hello, ${name.trim()}")
text
Name: Hello, Ann

Read the file named on the command line, or standard input when there is none. The deferred close is Ok for both:

ant
let args = Os.args()
let input = if args.isEmpty() { Os.stdin() } else { try File.open(args[0]) }
defer { input.close() }
var n = 0
while true {
  let line = try input.readLine() ?? break
  n += 1
  println("${n}: ${line}")
}
text
1: alpha
2: beta

Count the words of the input:

ant
let counts: Map[string, int] = Map{}
for word in (try File.readAll(Os.stdin())).fields() {
  let key = word.toLower()
  counts[key] = (counts[key] ?? 0) + 1
}
println(counts)
text
Map{ "the": 3, "cat": 1, "saw": 1, "dog": 1, "end": 1 }

Check whether the input comes from a terminal before reading it, so that a run without piped input prints a usage line instead of waiting at the terminal. The test's input is not a terminal:

ant
if Os.stdin().isTerminal() {
  eprintln("usage: tool < input")
  Os.exit(2)
}
let text = try File.readAll(Os.stdin())
println("${text.lines().length()} lines")
text
2 lines

Keep the lines that contain a word given as an argument, as grep does:

ant
let word = Os.args().first() ?? ""
let input = Os.stdin()
while true {
  let line = try input.readLine() ?? break
  if line.contains(word) {
    println(line)
  }
}
text
error: disk full
error: gave up

Properties and relations ​

Closing standard input leaves it open:

ant
let input = Os.stdin()
assert(input.close().isOk())
assert((try input.readLine()) == "still here")

Possible issues ​

A read gives string | null, so the line cannot be used before the end of the input is handled:

ant
let line = try Os.stdin().readLine()
println(line.toUpper())
// error: string | null has no field or function toUpper on every member: narrow the value first

See also ​

Os.stdout · Os.stderr · Os.args · File.readLine · File.readAll · File.readChunk · File.pipe · File.isTerminal · Cmd.run