open

The open static method can be used to open a file in read-only mode.

A File owns a resource, the file descriptor and takes care of closing the
file when it is droped.

  1. use std::error::Error;
  2. use std::fs::File;
  3. use std::io::prelude::*;
  4. use std::path::Path;
  5. fn main() {
  6. // Create a path to the desired file
  7. let path = Path::new("hello.txt");
  8. let display = path.display();
  9. // Open the path in read-only mode, returns `io::Result<File>`
  10. let mut file = match File::open(&path) {
  11. // The `description` method of `io::Error` returns a string that
  12. // describes the error
  13. Err(why) => panic!("couldn't open {}: {}", display,
  14. why.description()),
  15. Ok(file) => file,
  16. };
  17. // Read the file contents into a string, returns `io::Result<usize>`
  18. let mut s = String::new();
  19. match file.read_to_string(&mut s) {
  20. Err(why) => panic!("couldn't read {}: {}", display,
  21. why.description()),
  22. Ok(_) => print!("{} contains:\n{}", display, s),
  23. }
  24. // `file` goes out of scope, and the "hello.txt" file gets closed
  25. }

Here’s the expected successful output:

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

(You are encouraged to test the previous example under different failure
conditions: hello.txt doesn’t exist, or hello.txt is not readable,
etc.)