- 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.
推薦閱讀
- Java Web開發學習手冊
- OpenDaylight Cookbook
- 自己動手實現Lua:虛擬機、編譯器和標準庫
- Building a Game with Unity and Blender
- CentOS 7 Server Deployment Cookbook
- Functional Programming in JavaScript
- 小程序,巧運營:微信小程序運營招式大全
- Spring+Spring MVC+MyBatis整合開發實戰
- 用案例學Java Web整合開發
- Beginning C++ Game Programming
- scikit-learn Cookbook(Second Edition)
- C++17 By Example
- Mastering Drupal 8
- Learning Ionic(Second Edition)
- Learning SaltStack(Second Edition)