- 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.
推薦閱讀
- 少兒人工智能趣味入門:Scratch 3.0動畫與游戲編程
- Functional Python Programming
- 玩轉Scratch少兒趣味編程
- Learn TypeScript 3 by Building Web Applications
- TypeScript入門與實戰
- 零基礎搭建量化投資系統:以Python為工具
- Boost C++ Application Development Cookbook(Second Edition)
- 體驗設計原理:行為、情感和細節
- 技術領導力:程序員如何才能帶團隊
- 數據結構與算法JavaScript描述
- Learn Swift by Building Applications
- Python神經網絡項目實戰
- HTML5+CSS3網站設計基礎教程
- Mastering React
- 圖數據庫實戰