- 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.
推薦閱讀
- 從零構建知識圖譜:技術、方法與案例
- Kali Linux Web Penetration Testing Cookbook
- Visual C++程序設計學習筆記
- SQL Server 2012數據庫技術及應用(微課版·第5版)
- 劍指JVM:虛擬機實踐與性能調優
- MySQL 8 DBA基礎教程
- JS全書:JavaScript Web前端開發指南
- PySide GUI Application Development(Second Edition)
- PLC編程與調試技術(松下系列)
- Building RESTful Python Web Services
- PHP 7+MySQL 8動態網站開發從入門到精通(視頻教學版)
- PHP編程基礎與實例教程
- 持續輕量級Java EE開發:編寫可測試的代碼
- Android移動開發案例教程:基于Android Studio開發環境
- Developing SSRS Reports for Dynamics AX