An idiomatic way of redirecting STDIN to STDOUT

Trying to redirect bytes from io::stdin() into io::stdout(), I came up with the code below, which uses a Vec as a buffer. This solution feels a bit superfluous, since the BufReader and BufWriter should already have their own buffers, so maybe it is possible to plug the reader into the writer directly?

use std::io::{self, BufRead, BufReader, BufWriter, Write};

const BUFSIZE: usize = 8 * 1024;

fn main() {
    let mut reader = BufReader::with_capacity(BUFSIZE, io::stdin());
    let mut writer = BufWriter::with_capacity(BUFSIZE, io::stdout());

    // Do I really need this buffer?
    let mut buf = Vec::with_capacity(BUFSIZE);

    while let Ok(num) = reader.read_until(b'\n', &mut buf) {
        if num == 0 {


I think there is an io::copy function for coping from Read to Write.

1 Like

Perfect, thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.