How to check EOF on `read_line ()`?

Given the code below, how can I specifically test EOF? Rather, how can I distinguish between "there is nothing here" and "it exploded"?

match io::stdin().read_line() { Ok(l) => print!("{}", l), Err(_) => do_something_else(), } 
+11
source share
1 answer

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 thread has reached EOF.

This means that we can verify the 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(()) } 
+12
source

Source: https://habr.com/ru/post/1209030/


All Articles