Buffered I/O and locks

How do I read and write a bunch of integers(per line) from stdin to stdout by using BUFFERED i/o and holding LOCKS? Please provide a simple but COMPLETE(including "use") example.

The Stdin::read_line can be used data line-by-line, however it will release the lock between each line. Alternately you can lock stdin using Stdin::lock and read lines with a BufReader.

Once you have a line, you can use split_ascii_whitespace to split your line into individual integers, that you can parse using parse.

An alternative to reading stdin line-by-line is to read the entire thing using read_to_string and splitting one whitespace for the full file. Of course this requires that the input comes from e.g. a file and not typed by the user.

You can write to stdout using println!. If you run into trouble putting these together, feel free to ask specific questions regarding the parts you couldn't get to fit together.

Can you provide a simple code? I can't really connect BufReader and stdin and its lock. Same for stdout and BufWriter. I don't have that much time for reading the docs right now..

use std::io::BufRead;
let stdin = std::io::stdin();
let buffered = BufReader::new(stdin.lock());
buffered.read_line(&mut my_string);
1 Like

Alright..What do I do with the fourth line for a stdout?

You can print using println! or print!. If you want more help, please try yourself first, and post a code snippet along with the error you are getting.

Ok...thanks. I'll try later..I'm getting all info I can have now because my internet connection is limited. I'll try offline.

Keep in mind that you can open a local copy of the documentation using rustup doc.

1 Like

stdin().lock() returns a StdinLock which is a pointer to a BufReader. Because of this, it's not necessary to wrap it in an additional BufReader. So you can simplify this to:

use std::io::BufRead;
let stdin = std::io::stdin();
let mut buffered = stdin.lock();
buffered.read_line(&mut my_string)?;

stdout is a bit different; it uses a LineWriter. You might still want to wrap it in a BufWriter to avoid flushing after a single line:

use std::io::{Write, BufWriter, stdout};
let stdout = stdout();
let mut buffered = BufWriter::new(stdout.lock());
writeln!(buffered, "Hello, {}!", "world")?;

(There is a feature request to let stdout use a BufWriter internally instead of a LineWriter, when appropriate.)

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.