EndOfFile IoResult detection while reading a file

I am trying to read from a file in Rust. I don’t understand: when the BufferedReader is in EOF, it actually gives Err(IoError {kind: EndOfFile}) , and I don’t know how it can be combined.

 loop { match file.read_line() { Ok(line) => { // Do stuff }, // Err(EndOfFile) => is want I want here so I can call "break" Err(_) => { panic!("Unexpected error reading file."); } } } 

How can I explicitly map the EndOfFile enumeration EndOfFile ?

0
source share
3 answers

How can I explicitly map the EndOfFile enumeration option?

You can match it without additional nested matching using the following pattern:

 loop { match file.read_line() { Ok(line) => { // Do stuff }, Err(IoError { kind: EndOfFile, .. }) => break, Err(_) => { panic!("Unexpected error reading file."); } } } 
+6
source

especially for iterating over strings, rust has a lines function for buffers ( http://doc.rust-lang.org/std/io/trait.BufferPrelude.html#tymethod.lines ).

In your case, you will iterate over the lines, and after reaching the EOF, the cycle is terminated automatically without your intervention.

 for line in file.lines() { match line { Ok(line) => { // do stuff }, Err(_) => { println!("Unexpected error reading file.") } } } 

or, if your function returns a compatible Result , you can use try! macro for less noise:

 fn myfun(file: File) -> IoResult<()> { for line in file.lines() { let line = try!(line); // do stuff } } 
+3
source

It seems like rust 1.0 changed IoError to std::io::Error . In addition, kind now hidden in internal elements. I had to use guard to work with a similar problem ( WouldBlock instead of EndOfFile ).

eg.

 match some_method_that_might_block() { Ok(_) => { debug!("worked!"); }, Err(ref e @ IoError { kind: std::io::ErrorKind::WouldBlock, .. }) if e.kind() == std::io::ErrorKind::WouldBlock => { // ignore WouldBlock }, Err(e) => { debug!("error={:?}", e); } }; 
+1
source

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


All Articles