Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaner way to get the contents of a file as string in Rust? [duplicate]

Tags:

file-io

rust

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());
}
like image 409
Earlz Avatar asked Dec 14 '14 22:12

Earlz


1 Answers

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.

like image 173
Shepmaster Avatar answered Nov 12 '22 09:11

Shepmaster