通过例子学习Rust

46.1 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 take cares of closing the file when its droped.

use std::io::File; fn main() { // Create a path to the desired file let path = Path::new("hello.txt"); let display = path.display(); // Open the path in read-only mode, returns `IoResult<File>` let mut file = match File::open(&path) { // The `desc` field of `IoError` is a string that describes the error Err(why) => panic!("couldn't open {}: {}", display, why.desc), Ok(file) => file, }; // Read the file contents into a string, returns `IoResult<String>` match file.read_to_string() { Err(why) => panic!("couldn't read {}: {}", display, why.desc), Ok(string) => print!("{} contains:\n{}", display, string), } // `file` goes out of scope, and the "hello.txt" file gets closed }

The playpen doesn't allow file I/O, so you'll hit one of the failure paths. Here's the expected successful output:

$ echo "Hello World!" > hello.txt
$ rustc open.rs && ./open
hello.txt contains:
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.)