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

前端 未结 1 1960
别那么骄傲
别那么骄傲 2020-12-10 11:59

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:         


        
相关标签:
1条回答
  • 2020-12-10 12:30

    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(())
    }
    
    0 讨论(0)
提交回复
热议问题