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

  • Learning Rust
  • Paul Johnson Vesa Kaihlavirta
  • 126字
  • 2021-07-02 23:07:22

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.

主站蜘蛛池模板: 蒙自县| 馆陶县| 上栗县| 深州市| 阿荣旗| 衡水市| 赞皇县| 西畴县| 长宁县| 建阳市| 黑山县| 衡南县| 廉江市| 会昌县| 丰县| 措美县| 定安县| 凤城市| 斗六市| 偃师市| 尼勒克县| 琼结县| 黎川县| 兴文县| 安新县| 宜城市| 筠连县| 张掖市| 潜山县| 潮安县| 冀州市| 孙吴县| 沈丘县| 迭部县| 合江县| 铜川市| 北宁市| 交城县| 大城县| 东丽区| 基隆市|