打开文件 open

open 静态方法能够以只读模式(read-only mode)打开一个文件。

File 拥有资源,即文件描述符(file descriptor),它会在自身被 drop 时关闭文件。

  1. use std::fs::File;
  2. use std::io::prelude::*;
  3. use std::path::Path;
  4. fn main() {
  5. // 创建指向所需的文件的路径
  6. let path = Path::new("hello.txt");
  7. let display = path.display();
  8. // 以只读方式打开路径,返回 `io::Result<File>`
  9. let mut file = match File::open(&path) {
  10. // `io::Error` 的 `description` 方法返回一个描述错误的字符串。
  11. Err(why) => panic!("couldn't open {}: {:?}", display, why),
  12. Ok(file) => file,
  13. };
  14. // 读取文件内容到一个字符串,返回 `io::Result<usize>`
  15. let mut s = String::new();
  16. match file.read_to_string(&mut s) {
  17. Err(why) => panic!("couldn't read {}: {:?}", display, why),
  18. Ok(_) => print!("{} contains:\n{}", display, s),
  19. }
  20. // `file` 离开作用域,并且 `hello.txt` 文件将被关闭。
  21. }

下面是所希望的成功的输出:

  1. $ echo "Hello World!" > hello.txt
  2. $ rustc open.rs && ./open
  3. hello.txt contains:
  4. Hello World!

(我们鼓励您在不同的失败条件下测试前面的例子:hello.txt 不存在,或 hello.txt 不可读,等等。)