Search code examples
rust

Canonicalize file path string containing current directory with a given directory


Is it possible to canonicalize a file path string containing current directory (.) with a given directory. For e.g, file path => ./abcd.txt, given directory => /a/b/c. The expected result of the resulting file path is /a/b/c/abcd.txt.

fn main() {
    let file_path = "./abcd.txt";
    let cur_dir = "/a/b/c";
    
    let path = std::fs::canonicalize(file_path).unwrap();
    println!("{:#?}", path);
}

Output

thread 'main' panicked at src/main.rs:5:49:
called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Solution

  • Use Path::join:

    let path = Path::new (cur_dir).join (file_path).canonicalize();