RRust By Example
intermediateFile I/O

Path Operations

Work with file paths using Path and PathBuf.

Path Operations

Work with file paths using Path and PathBuf.

Difficulty

Intermediate

Code

rust
use std::path::{Path, PathBuf};

fn main() {
    let path = Path::new("/home/user/documents/file.txt");

    println!("full: {}", path.display());
    println!("file name: {:?}", path.file_name());
    println!("extension: {:?}", path.extension());
    println!("parent: {:?}", path.parent());
    println!("stem: {:?}", path.file_stem());

    // build paths
    let mut base = PathBuf::from("/home/user");
    base.push("documents");
    base.push("file.txt");
    println!("built: {}", base.display());

    // change extension
    base.set_extension("md");
    println!("changed: {}", base.display());

    // check existence
    let p = Path::new("Cargo.toml");
    println!("exists: {}", p.exists());
    println!("is_file: {}", p.is_file());
}

Explanation

Path/PathBuf handle file paths cross-platform.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the file-io category to build a complete understanding of this topic.

More File I/O Examples