官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 随州市| 临沧市| 浮梁县| 南木林县| 白沙| 新河县| 耿马| 刚察县| 乐至县| 延津县| 宜兰县| 建水县| 临武县| 霍邱县| 介休市| 谢通门县| 夏津县| 焉耆| 浦江县| 德庆县| 桐城市| 孟村| 汝州市| 顺义区| 惠东县| 溧水县| 咸阳市| 阿拉善右旗| 织金县| 天津市| 灌云县| 石渠县| 区。| 烟台市| 遂平县| 江川县| 山阴县| 肥东县| 巴彦县| 三明市| 射洪县|