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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 2, 2024 (new example).