As my first dive into Rust in a while, I started writing code to dump the contents of a file to a string, for later processing (right now I'm just printing it out though)
Is there a cleaner way to do this than I currently am? It seems like I'm having to be way too verbose about it, but I'm not seeing any good way to clean it up
use std::io;
use std::io::File;
use std::os;
use std::str;
fn main() {
println!("meh");
let filename = &os::args()[1];
let contents = match File::open(&Path::new(filename)).read_to_end() {
Ok(s) => str::from_utf8(s.as_slice()).expect("this shouldn't happen").to_string(),
Err(e) => "".to_string(),
};
println!("ugh {}", contents.to_string());
}
Editor's note: review the linked duplicate for a maintained answer with shorter / cleaner answers.
Read::read_to_string
is the shortest I know of:
use std::io::prelude::*;
use std::fs::File;
fn main() {
let mut file = File::open("/etc/hosts").expect("Unable to open the file");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Unable to read the file");
println!("{}", contents);
}
Having to think about failure cases is something that Rust likes to place front and center.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With