0

(Very similar question, excluding CWD support: How to check whether a path exists?)

I want to check whether a file-system paths parent directory - given as string - exists, also if that parent is the CWD, indicated as "".

In my specific case, I get a local file path as CLI argument, that points to the output/result file of my software. The file does not have to exist, but it's parent dir has to exist, which I check with Path::new(out_file).parent()?.exists(). If out_file is for example "out.txt", it's parent will be "", Which will always return false for the exists() call, because Rust does not interpret Path::new("") as CWD.

hoijui
  • 3,615
  • 2
  • 33
  • 41

1 Answers1

0

credits go to @chai.t.rex on the rust discord channel:

/**
 * Returns the path to the parent dir of the argument, if it has one.
 * We use this rather complex way of doing it,
 * because with a simple `file_path.parent()?.exists()`,
 * we would get `false` in case of `"bla.txt"`,
 * even if CWD is an existing directory.
 */
fn get_parent<P>(file_path: P) -> Option<PathBuf>
where
    P: AsRef<Path>,
{
    let file_path_val = file_path.as_ref();
    let parent = file_path_val.parent()?;
    if parent.components().next().is_none() {
        return current_dir().ok();
    }
    Some(parent.to_owned())
}
hoijui
  • 3,615
  • 2
  • 33
  • 41