[solved] How do you work with relative paths

I'm trying to write a small routine too create a new directory if it does not exists.

The code should be able to operate on relative directories as I want it to default to "~/" if no other base path has been set.

Looking at the docs for std::fs or std::path it seems that there is not way to expand "~/" to its absolute path. The closes there is seems to be Path in std::path - Rust but it does not work on paths that does not exists (which is my starting problem).

Any pointers for how to work with relative paths in rust?

~/ isn't really a relative path. The ~ sigil is typically expanded by your shell. e.g., Try echo ~.

If you want to use ~/ as a default, then you probably just want to get the value of $HOME instead. e.g.,

use std::env;
use std::process;

fn main() {
    let path = match env::var_os("HOME") {
        None => { println!("$HOME not set."); process::exit(1) }
        Some(path) => PathBuf::from(path),
    };
    println!("default path: {}", path.display());
}

(Warning: did not check above code with compiler.)

Ah true that. Thanks

This is better written with home_dir in std::env - Rust, which will do more things and works across platforms.

2 Likes

Nice, totally missed that function in std::env.

Thanks

So did I! Thanks @steveklabnik :slight_smile: