Created
August 30, 2020 14:14
-
-
Save innermond/3db8fad1bccac4bcd357dacb8d41e833 to your computer and use it in GitHub Desktop.
reading a file in rust using buffered reader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io; | |
use std::io::prelude::*; | |
use std::io::BufReader; | |
fn main() { | |
let s = match read_as_string("<path/to/file>".to_string()) { | |
Ok(content) => content, | |
Err(e) => format!("{:?}", e), | |
}; | |
println!("{}", s); | |
} | |
fn read_as_string(n: String) -> Result<String, io::Error> { | |
let mut s = String::new(); | |
let f = File::open(n)?; | |
let mut r = BufReader::new(f); | |
while match r.read_line(&mut s) { | |
// 0 means eof | |
Ok(0) => false, | |
// error | |
Err(e) => return Err(e), | |
// read was a success | |
_ => true, | |
}{} | |
Ok(s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment