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

  • 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.

主站蜘蛛池模板: 屯昌县| 瑞金市| 松溪县| 宁南县| 泰和县| 徐水县| 筠连县| 抚松县| 芒康县| 九江县| 伊川县| 杭锦旗| 扶绥县| 教育| 蓬溪县| 博客| 合山市| 正宁县| 盐城市| 徐闻县| 广汉市| 敦化市| 永丰县| 松原市| 营口市| 西城区| 蓝田县| 通渭县| 三穗县| 红原县| 珠海市| 榆林市| 铜川市| 浏阳市| 阳春市| 明水县| 读书| 丹江口市| 上栗县| 甘泉县| 夏河县|