PathBuf
How can we build up a path containing a directory and a file name in a reliable way in Rust? We can use PathBuf
, along with methods like current_dir()
.
With the env current_dir()
method, we can get a PathBuf
containing the current directory. This is the directory the user is running the program in.
This Rust example program uses the PathBuf
and Path
types in a variety of ways. It gets a PathBuf
from current_dir()
on the env type.
current_dir()
.PathBuf
can also be created directly from a string
. We can call push()
to add another part to the path (either a directory or file).as_path()
we can use Path
methods, such as exists()
—this tells us if the file exists.str
or a String
. The to_str()
(and to_string
) methods can be used to open files from the disk.use std::env; use std::path::PathBuf; fn main() { // Part 1: get current directory, and push a file name onto it. let mut c = env::current_dir().unwrap(); c.push("test.txt"); println!("{:?}", c); // Part 2: create a PathBuf from a string, and add a directory and file name to it. let mut p = PathBuf::from("home"); p.push("directory"); p.push("test.png"); println!("{:?}", p); // Part 3: create a PathBuf, and get a Path from it, and finally see if the Path exists. let mut p2 = env::current_dir().unwrap(); p2.push("Cargo.toml"); let path = p2.as_path(); println!("{:?} EXISTS = {}", path, path.exists()); // Part 4: get a str (this can be used to open a file). let mut p3 = PathBuf::from("test"); p3.push("file.xml"); let s = p3.to_str().unwrap(); println!("{} LENGTH = {}", s, s.len()); }"C:\\Users\\mount\\OneDrive \\Documents\\programs\\hello-rust\\test.txt" "home\\file.txt" "C:\\Users\\mount\\OneDrive \\Documents\\programs\\hello-rust\\Cargo.toml" EXISTS = true test\file.xml LENGTH = 13
Path
Similar to how str
and String
work in Rust, we can use the Path
type to receive PathBuf
objects. This makes methods more versatile in the types they can handle.
use std::path::*; fn test(p: &Path) { // We can receive a PathBuf as a Path reference. let value = p.to_str().unwrap(); println!("{}", value); } fn main() { // Pass a PathBuf to a method that handles Path. let mut p = PathBuf::from("home"); p.push("test.txt"); test(&p); }home\test.txt
Using a PathBuf
is the easiest way to build up path strings in a reliable way in Rust. We can then access the result as a path or a String
, for later use in the program.