Skip to content

Instantly share code, notes, and snippets.

@innermond
Created August 30, 2020 14:14
Show Gist options
  • Save innermond/3db8fad1bccac4bcd357dacb8d41e833 to your computer and use it in GitHub Desktop.
Save innermond/3db8fad1bccac4bcd357dacb8d41e833 to your computer and use it in GitHub Desktop.
reading a file in rust using buffered reader
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