Working with files
Now we show you how to do common operations with files, such as reading and writing, and making folders, and at the same time do proper error handling. The modules that contain these functionalities are std::path
, which provides for cross platform file path manipulation, and std::fs
.
Paths
File paths from the underlying file system are represented by the Path
struct, which is created from a string slice containing the full path with Path::new
. Suppose hello.txt
is an existing file in the current directory; let's write some code to explore it:
// code from Chapter 11/code/paths.rs:use std::path::Path; fn main() { let path = Path::new("hello.txt"); let display = path.display(); // test whether path exists: if path.exists() { println!("{} exists", display); } else { panic!("This path or file does not exist!"); } let file = path.file_name().unwrap(); let extension = path.extension().unwrap(); let parent_dir = path...