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.
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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 2, 2024 (new example).