admin管理员组

文章数量:1287526

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

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
Share Improve this question asked Feb 25 at 7:14 HarryHarry 3,0521 gold badge24 silver badges46 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

Use Path::join:

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

本文标签: rustCanonicalize file path string containing current directory with a given directoryStack Overflow