- 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.
推薦閱讀
- Learn to Create WordPress Themes by Building 5 Projects
- PHP基礎(chǔ)案例教程
- Mastering Kali Linux for Web Penetration Testing
- Python數(shù)據(jù)挖掘與機(jī)器學(xué)習(xí)實(shí)戰(zhàn)
- Mastering Android Game Development
- 常用工具軟件立體化教程(微課版)
- 新一代SDN:VMware NSX 網(wǎng)絡(luò)原理與實(shí)踐
- C++反匯編與逆向分析技術(shù)揭秘(第2版)
- 深入淺出Go語(yǔ)言編程
- 移動(dòng)增值應(yīng)用開(kāi)發(fā)技術(shù)導(dǎo)論
- C++ Fundamentals
- Scratch·愛(ài)編程的藝術(shù)家
- Learning iOS Security
- CodeIgniter Web Application Blueprints
- Python+Office:輕松實(shí)現(xiàn)Python辦公自動(dòng)化