Sub topic 9
Processing many lines with a locked stdin and lines()
This chapter assumes you can already read one line with read_line, handle its io::Result with ?, and parse text with parse. It also assumes you know what String and &str are and how to run a program with cargo run. Here you move from "one line" to "all the lines until the input ends".
The problem with a manual loop
You can read many lines by calling read_line in a loop. You then have to do three things yourself:
- Create or clear a
Stringon every pass.read_lineappends, so a reused buffer grows unless you callclear(). - Check for
Ok(0), which means end of input. - Remember that the newline is still on the end of each line.
The lines() method does all three for you. It turns a reader into an iterator, so a for loop can walk through the input and stop at the end by itself.
What "locking" means
io::stdin() returns a Stdin handle. Every program has one shared, buffered copy of standard input behind a mutex. A mutex is a lock that lets only one piece of code use a resource at a time. Each call such as stdin.read_line(...) takes that mutex, reads, and releases it.
stdin.lock() takes the mutex once and gives you a StdinLock. That value owns the lock until you drop it. Two things follow:
- You pay the locking cost once, not on every line.
StdinLockimplements theBufReadtrait.BufReadis the trait that provideslines(),read_line, and other buffered-reading methods.
Since Rust 1.61, lock() returns a StdinLock<'static>. It does not borrow from the Stdin value, so you can write io::stdin().lock() in a single expression without keeping the handle in a variable.
The basic pattern
This program reads every line, splits it into whitespace-separated words, parses each word as a number, and adds the numbers up.
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut sum: i64 = 0;
for line in io::stdin().lock().lines() {
let line = line?;
for token in line.split_whitespace() {
match token.parse::<i64>() {
Ok(n) => sum += n,
Err(_) => eprintln!("skipping {token:?}"),
}
}
}
println!("sum = {sum}");
Ok(())
}Try it by piping input:
printf '1 2 3\n4 five 6\n' | cargo runThe program prints skipping "five" to standard error and then sum = 16.
Points to notice:
use std::io::BufReadis required. Without the trait in scope, the compiler reports that no method namedlinesexists onStdinLock, even though the type clearly has it.- Each item is an
io::Result<String>, not aString. Reading can fail, so every line arrives wrapped in aResult. The linelet line = line?;unwraps it and shadows the name. mainreturnsio::Result<()>, so?can return the error frommain.- Error messages for bad tokens go to
eprintln!, which writes to standard error. That keeps the sum on standard output clean if someone redirects it. - Splitting a line into tokens is covered in its own chapter. Here it only gives the loop something to do.
What lines() does to each line
| Behavior | Detail |
|---|---|
| Item type | `io::Result<String>`, a new `String` for each line |
| Line ending | A trailing `\n` or `\r\n` is removed. Spaces and tabs at the end stay. |
| Blank lines | They yield an empty string `""`. They are not skipped. |
| Last line | A final line with no newline is still yielded. |
| End of input | The iterator returns `None`. You never see `Ok(0)`. |
| Invalid UTF-8 | The item is an `Err` of kind `InvalidData`. |
Because lines() removes the line ending, you do not need trim_end_matches('\n'). You may still want trim() if the input can have stray spaces around the value.
The flow of one pass through the loop looks like this:
Using iterator adapters
lines() returns an ordinary iterator, so adapters such as enumerate, take, and filter work on it. This example numbers the non-blank lines of its input:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
for (i, line) in io::stdin().lock().lines().enumerate() {
let line = line?;
if line.trim().is_empty() {
continue;
}
println!("{:>3}: {}", i + 1, line);
}
Ok(())
}enumerate counts every line, including blank ones. The numbers therefore match the line numbers in the original input, and a blank line leaves a gap in the printed numbers.
Many programmers shorten error handling with .map_while(Result::ok) or .flatten(). Both discard the Err values without telling you.
use std::io::{self, BufRead};
fn main() {
let count = io::stdin()
.lock()
.lines()
.map_while(Result::ok)
.count();
println!("{count} lines");
}This compiles and works for clean input. If the input contains invalid UTF-8, the loop stops quietly and the count is wrong. .flatten() is worse. After an I/O error some readers keep returning the same error, so .flatten() can loop forever. Prefer line? unless you have decided that errors do not matter.
Interactive use and end of input
lines() works with a keyboard as well as with a pipe. The loop blocks until you press Enter, handles the line, and waits again. It ends when the input does:
- On Linux and macOS, press Ctrl-D on an empty line.
- On Windows, press Ctrl-Z and then Enter.
- With a pipe or a redirected file, it ends when the data runs out.
Unlike the earlier prompt-and-retry program, a plain for loop over lines() shows no prompt. If you want one, you need print! and io::stdout().flush() inside the loop, as shown in the prompt chapter. Be aware that Ctrl-D can then arrive while a prompt is displayed, so print a newline after the loop ends.
Gotchas
Do not mix the lock with other reads
A safe pattern is to take the lock once, in the place where you start the loop, and pass it or its lines down to helper functions.
Memory and speed
lines() allocates a new String for every line. For small inputs this does not matter. If you process millions of lines, you can reuse one buffer with read_line on the locked handle:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut stdin = io::stdin().lock();
let mut buf = String::new();
let mut count = 0usize;
loop {
buf.clear();
if stdin.read_line(&mut buf)? == 0 {
break;
}
count += 1;
}
println!("{count} lines");
Ok(())
}Here the buffer is cleared at the top of each pass, and Ok(0) ends the loop. Note that buf still contains the newline, so call trim_end() if you need the text only. Start with lines(). Switch to this form only when measurement shows that allocation matters.
Huge lines and huge input
lines() reads a whole line into memory before giving it to you. A file with no newlines at all is one enormous line. If the input might come from an untrusted source, consider limiting how much you read, for example with Read::take, before building lines from it.
Stopping early
You can leave the loop with break before the input ends. The unread data stays in the shared stdin buffer, so a later read on io::stdin() continues from that point.
Choosing between the approaches
| Situation | Use |
|---|---|
| Ask one question, get one answer | `read_line` once |
| Re-prompt until the answer is valid | `read_line` in a loop |
| Process every line of piped or typed input | `lock().lines()` |
| Millions of lines, allocation matters | `lock()` with a reused buffer and `read_line` |
| You need the whole input as one value | `read_to_string` (a later chapter) |
Looking ahead
Because lines() comes from the BufRead trait, any function that takes a BufRead can use it. That includes a StdinLock, a buffered file, and a byte slice such as "1\n2\n".as_bytes(). The testing chapter builds on this idea. If you write your loop inside a function that takes R: BufRead, you can test it without a terminal.
Exercise
A program reads input with for line in io::stdin().lock().lines() and prints line.len() for each line. You give it the text "ab\r\n\ncd" (a line with a Windows line ending, an empty line, and a last line with no newline). What does it print, and why?
Show answer
It prints 2, 0, and 2, on three separate lines. lines() removes the "\r\n" from the first line, so it yields "ab" with length 2. The empty line is not skipped, so it yields "" with length 0. The last line has no trailing newline, but lines() still yields it, so "cd" has length 2.
Exercise
A student writes let lock = io::stdin().lock(); at the top of main, then later inside a loop calls io::stdin().read_line(&mut s)?. What is likely to happen, and how do you fix it?
Show answer
The second call tries to take the stdin mutex that lock already holds on the same thread, so the program can hang (deadlock). Fix it by calling read_line on the locked handle itself (lock.read_line(&mut s)? with lock declared mut), or by dropping the lock before using io::stdin() again.