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.parent().unwrap(); println!("This is file {:?} with extension {:?} in folder {:?}", file, extension, parent_dir); // Check if the path is a file: if path.is_file() { println!("{} is a file", display); } // Check if the path is a directory: if path.is_dir() { println!("{} is a directory", display); } }
This code performs the following:
- Prints: This is file "hello.txt" with extension "txt" in folder "".
- The Path::new("e.txt").unwrap_or_else() method creates the file e.txt or panics with an error.
- Tests whether a path is valid. Use the exists() method.
- Uses the create_dir() method to make folders.
- The file_name(), extension() and parent() methods return an Option value, so use unwrap() to get the value. The is_file() and is_dir() methods test respectively whether a path refers to a filename or to a directory.
- The join() method can be used to build paths, and it automatically uses the operating system-specific separator:
let new_path = path.join("abc").join("def"); // Convert the path into a string slice match new_path.to_str() { None => panic!("new path is not a valid UTF-8 sequence"), Some(s) => println!("new path is {}", s), }
- This prints out the following on a Windows system:
new path is hello.txt\abc\def