November 2017
Intermediate to advanced
264 pages
5h 45m
English
The File struct from std::fs represents a file that has been opened (it wraps a file descriptor), and gives read and/or write access to the underlying file.
Since many things can go wrong when doing file I/O, explicit and proactive handling of all possible errors is certainly needed. This can be done with pattern matching, because all the File methods return the std::io::Result<T> type, which is an alias for Result<T, io::Error>.
To open a file in read-only mode, use the static File::open method with a reference to its path, and match the file handler or a possible error like this:
// code from Chapter 11/code/read_file.rs:
use std::path::Path;
use std::fs::File; use std::io::prelude::*; use std::error::Error; fn main() { let ...Read now
Unlock full access