Canonicalize Resolves Dot Segments

Resolve a path containing dot segments with fs::canonicalize, confirm it becomes absolute, and compare it with the original file.

RustSecurity Boundaries

Code

rustsnippet
24 lines
use std::fs;

fn main() -> std::io::Result<()> {
    let root = std::env::temp_dir().join("canonicalize_demo");
    let nested = root.join("a").join("b");
    fs::create_dir_all(&nested)?;
    fs::write(nested.join("config.txt"), b"port = 8080\n")?;

    // a path with dot segments still points at the same file
    let messy = root.join("a").join("b").join("..").join("b").join("config.txt");
    println!("messy exists: {}", messy.exists());

    // canonicalize resolves dot segments and returns an absolute path
    let resolved = fs::canonicalize(&messy)?;
    println!("absolute: {}", resolved.is_absolute());
    println!("file name: {:?}", resolved.file_name());
    println!("same file: {}", fs::canonicalize(nested.join("config.txt"))? == resolved);

    // the original path keeps its dot segments
    println!("messy keeps dots: {}", messy.to_string_lossy().contains(".."));

    fs::remove_dir_all(&root)?;
    Ok(())
}

How it works

Count the function main as the entire surface area of Canonicalize Resolves Dot Segments.

Fallible operations return Result, and the ? operator short-circuits errors up to the caller.

Points of care

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Entry signature: fn main() -> std::io::Result<()>

Running the file prints labeled results such as messy exists:, absolute:, file name: — each operation’s effect is visible in the output.

Key statements

fs::write(nested.join("config.txt"), b"port = 8080\n")?;
let resolved = fs::canonicalize(&messy)?;
fs::create_dir_all(&nested)?;

Interactive Tools for This Topic

FAQ

What is the error handling style?
Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does Canonicalize Resolves Dot Segments print when run?
Invoke the file as-is — the `messy exists:`, `absolute:`, `file name:` prefixes identify which step printed each line.