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

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.

主站蜘蛛池模板: 什邡市| 宜城市| 巴塘县| 江都市| 山阴县| 安新县| 四子王旗| 台中市| 白玉县| 平陆县| 吉安县| 博乐市| 南昌县| 辽中县| 改则县| 宁化县| 佛坪县| 阳信县| 洞头县| 仲巴县| 满城县| 驻马店市| 绥棱县| 梓潼县| 常德市| 彰武县| 泸定县| 修文县| 太保市| 丹东市| 巴里| 新邵县| 太白县| 富平县| 罗山县| 临邑县| 常宁市| 丹江口市| 嫩江县| 集安市| 大竹县|