Read standard input line by line
This program prints each line of its standard input with its number. Save it as number.ant and pipe text into it with printf 'apple\nbanana\n' | ant run number.ant:
let input = Os.stdin()
var n = 0
while true {
let line = try input.readLine() ?? break
n += 1
println("${n}: ${line}")
}1: apple
2: banana- Get the handle of standard input with Os.stdin.
- Call File.readLine in a loop. Each call returns the next line without its
\nor\r\n, an empty line as"", andnullat the end of the input. - End the loop at
nullwith?? break.tryends the script on a read error, writes the error to standard error and exits with status 1. - Handle the line, here with println.
Write many lines fast
Standard output is not buffered. For a large input, write through File.buffered and close the buffered handle at the end with File.close, which writes out what it holds:
let input = Os.stdin()
let out = Os.stdout().buffered()
defer { out.close() }
while true {
let line = try input.readLine() ?? break
try out.writeLine(line.toUpper())
}
try out.close()APPLE
BANANAFile.writeLine writes each line to the buffer, and String.toUpper upper-cases each line. The deferred close writes out what the buffer holds when a read error ends the script; the final try out.close() reports an error from writing it out.
Read a file or standard input
Read the file named by the first argument, or standard input when there is none, and print the length of each line. Get the arguments with Os.args, check for none with Array.isEmpty, open the file with File.open and measure each line with String.length. Closing standard input does nothing, so one defer serves both:
let args = Os.args()
let input = if args.isEmpty() { Os.stdin() } else { try File.open(args[0]) }
defer { input.close() }
while true {
let line = try input.readLine() ?? break
println(line.length())
}5
6Read all of standard input at once
To get the whole input as one string instead of a loop, call File.readAll. It waits for the end of the input:
let text = try Os.stdin().readAll()
println(text.length())13