Canonicalize Resolves Dot Segments
Resolve a path containing dot segments with fs::canonicalize, confirm it becomes absolute, and compare it with the original file.
Code
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 ownmatch.
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.