Loading a file

To open a file, we use File::open(filename). We can catch exceptions using the try! macro or match, as follows:

let file = try!(File::open("my_file.txt")) 

Or the following can be used:

let file = match File::open("my_file.txt") { 
    Ok(file) => file, 
    Err(..) => panic!("boom"), 
} 

If the file is available to open, File::open will grant read permissions to the file. To load the file, we create a BufReader based on the file:

let mut reader = BufReader::new(&file); 
let buffer_string = &mut String::new(); 
reader.read_line(buffer_string); 
println!("Line read in: {}", buffer_string); 

Once the file has been read, the stream can be explicitly closed with reader.close(). However, Rust's resource management system guarantees that the file will be closed when its binding goes out of scope, so this is not mandatory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset