Rust input/output: Difference between revisions
From wikinotes
Line 28: | Line 28: | ||
print!("START\n{}\nFINISH\n", lines.join("\n")); | print!("START\n{}\nFINISH\n", lines.join("\n")); | ||
</syntaxhighlight> | </syntaxhighlight> | ||
manually buffered read from stdin (wait indefinitely if no pipe on stdin) | |||
<syntaxhighlight lang="rust"> | |||
fn buffered_read() { | |||
let mut buffer: [u8; 8] = [0; 8]; | |||
let stdin = io::stdin(); | |||
let mut handle = stdin.lock(); | |||
loop { | |||
let bytes_read = handle | |||
.read(&mut buffer[..]) | |||
.unwrap_or(0); | |||
// reached EOF | |||
if bytes_read == 0 { | |||
break; | |||
} | |||
print!("{}", str::from_utf8(&buffer).unwrap()); | |||
} | |||
} | |||
</syntaxhighlight> | |||
{{ TODO | | {{ TODO | |
Revision as of 07:40, 9 February 2023
Documentation
std::fs
https://doc.rust-lang.org/std/fs/index.html
Stdin, Stdout, Stderr
println!("out"); // write to stdout eprintln!("err"); // write to stderrread from stdin (wait indefinitely if nothing is written)
use std::io; use std::io::BufRead; let stdin = io::stdin(); let handle = stdin.lock(); let lines: Vec<String> = handle .lines() .map(|res| res.unwrap_or_default()) .collect(); print!("START\n{}\nFINISH\n", lines.join("\n"));manually buffered read from stdin (wait indefinitely if no pipe on stdin)
fn buffered_read() { let mut buffer: [u8; 8] = [0; 8]; let stdin = io::stdin(); let mut handle = stdin.lock(); loop { let bytes_read = handle .read(&mut buffer[..]) .unwrap_or(0); // reached EOF if bytes_read == 0 { break; } print!("{}", str::from_utf8(&buffer).unwrap()); } }
TODO:
read from stdin, checking if it's a tty or a pipe
User Input
let name = String::new(); io::stdin().read_line(&mut name);