dqxyh48864 2015-01-19 12:31
浏览 540
已采纳

检查给定路径是否是golang中另一个路径的子目录

Say we have two paths:

c:\foo\bar\baz and c:\foo\bar

Is there any package/method that will help me determine if one is a subdirectory of another? I am looking at a cross-platform option.

  • 写回答

2条回答 默认 最新

  • dprnr5559 2015-01-19 12:41
    关注

    You could try and use path.filepath.Rel():

    func Rel(basepath, targpath string) (string, error)
    

    Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator.
    That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself

    That means Rel("c:\foo\bar", "c:\foo\bar\baz") should be baz, meaning a subpath completely included in c:\foo\bar\baz, and without any '../'.
    The same would apply for unix paths.

    That would make c:\foo\bar\baz a subdirectory of c:\foo\bar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?