Returning an error on STDIN EOF with io::read_line()


I’ve been using the following function to read a single line of input in my program:

fn input() -> io::Result<String> {
    let mut string = String::new();
    let bytes_read = try!(io::stdin().read_line(&mut string));
    if bytes_read == 0 {
        return Err(io::Error::new(io::ErrorKind::Other,
                        "The line could not be read.");
    string = string.trim_right_matches("\r\n").to_owned();
    string = string.trim_right_matches("\n").to_owned();
    return string;

If the number of bytes read is 0, then STDIN is closed. However, this function doesn’t work: it allows a single line of empty input to be returned after STDIN has been closed. Only after that does the bytes_read error kick in.

Is it possible to modify this function to return an error right after STDIN is closed?


That method is probably more suited for reading files, where the last line doesn’t necessarily end with a line terminator. But I agree that for streaming, this is often not wanted.

I’ve implemented a read_line method in my netio crate that returns an error if no line terminator is found. If only works for CRLF though, because this is the standard in networking.