Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for EOF with `read_line()`?

Tags:

rust

Given the code below, how can I specifically check for EOF? Or rather, how can I distinguish between "there's nothing here" and "it exploded"?

match io::stdin().read_line() {
    Ok(l) => print!("{}", l),
    Err(_) => do_something_else(),
}
like image 834
mkaito Avatar asked Dec 14 '14 22:12

mkaito


1 Answers

From the documentation for read_line:

If successful, this function will return the total number of bytes read.

If this function returns Ok(0), the stream has reached EOF.

This means we can check for a successful value of zero:

use std::io::{self, BufRead};

fn main() -> io::Result<()> {
    let mut empty: &[u8] = &[];
    let mut buffer = String::new();

    let bytes = empty.read_line(&mut buffer)?;
    if bytes == 0 {
        println!("EOF reached");
    }

    Ok(())
}
like image 188
Shepmaster Avatar answered Oct 07 '22 20:10

Shepmaster