Check whether a directory is a subdirectory of another directory


This is not a very trivial task. In Python there is a method for this:

        from pathlib import Path
        if dst_dir.is_relative_to(src_dir):
            print("Error: dst_dir is inside src_dir")

dst_dir and src_dir being Path objects. What's the best approach to this problem with Rust?

Assuming dst_dir and src_dir are std::path::Path "objects", you'd use dst_dir.starts_with(src_dir). You can check the docs here.

Thanks! It works as expected.

Please note that starts_with is purely lexical and does not necessarily reflect whether the paths are actually nested in the filesystem because symlinks are a thing. You might want to call canonicalize first on both paths (although that does require both paths to actually exist).

1 Like

Thanks! Fortunately, it so happens that I work with the right kind of paths.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.