Read Stdin until EOF

I am trying to read Stdin until someone types CRTL-D.

use std::io;
use std::io::Read;

fn main() {
    let mut input =  Vec::new();
    let stdin = std::io::stdin();
    let mut handle = stdin.lock();
    handle.read_to_end(&mut input);
}

However I have to press CRTL-D twice for it to stop.

I think the first ctrl-d, deletes the current input line in your shell and the second gets sent to the program.

If you hit "enter" before the ctrl-d it works?

What shell or OS are you using?

I was wrong according to my testing and this stack exchange and the first ctrl-d sends the line through to the read() kind of like a newline does.

I would suggest reading this prior thread.

2 Likes

Thank you :grinning:.
You were right and I also found the answer on StackOverflow.

"On Unix-like systems (at least by default), an end-of-file condition is triggered by typing Ctrl-D at the beginning of a line or by typing Ctrl-D twice if you're not at the beginning of a line."

"EOF (not to be confused with the C EOF macro) is mapped by default to Ctrl-D. Typing the EOF character at the beginning of a line (either at the very beginning of the input or immediately after a newline) triggers an immediate end-of-file condition. Typing the EOF character other than at the beginning of a line causes the previous data on that line to be returned immediately by the next read() call that asks for enough bytes; typing the EOF character again does the same thing, but in that case there are no remaining bytes to be read and an end-of-file condition is triggered. A single EOF character in the middle of a line is discarded (if ICANON is set, which it normally is)."

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.