检查文件是否在给定目录中。

huangapple go评论85阅读模式
英文:

Checking if a file is in a given directory

问题

我有一个情况,我想检查一个特定路径是否位于一个特定目录内。我的第一反应是这样做:

filepath.HasPrefix(filepath.Clean(path), dir)

但是filepath.HasPrefix这个过程只是出于历史原因而存在。如果我使用strings.HasPrefix,会得到相同的效果吗?还是我漏掉了什么?

英文:

I've got a situation where I'd like to check whether a particular path lands inside of a particular directory. My first instinct was to do something like

filepath.HasPrefix(filepath.Clean(path), dir)

but the procedure filepath.HasPrefix is documented as existing for historic reasons only. Am I going to get the same effect by using strings.HasPrefix, or is there something I'm missing?

答案1

得分: 3

你没有错过任何东西,看看源代码:

// HasPrefix存在于历史兼容性,不应该使用。
func HasPrefix(p, prefix string) bool {
    return strings.HasPrefix(p, prefix)
}

直接使用strings.HasPrefix(p, prefix)即可。

英文:

You're not missing anything, look at the source:

// HasPrefix exists for historical compatibility and should not be used.
func HasPrefix(p, prefix string) bool {
	return strings.HasPrefix(p, prefix)
}

Just use strings.HasPrefix(p, prefix) directly.

答案2

得分: 2

虽然使用strings.HasPrefix可以获得相同的功能,但它并不适用于所有情况。filepath.HasPrefix被弃用是有原因的,它的方法也应被视为已弃用。

考虑filename=/foo/barprefix=/fo。这个测试通过了strings.HasPrefix,但显然bar不在/fo中。

正确的方法是将每个目录名作为一个整体进行比较。

英文:

While you will get the same functionality with strings.HasPrefix, it doesn't work in general. filepath.HasPrefix is deprecated for a reason and it's approach should be considered deprecated too.

Consider filename=/foo/bar and prefix=/fo. This passes the strings.HasPrefix test but clearly bar is not in /fo.

The proper approach would compare each directory name holistically.

答案3

得分: 0

在Go 1.4中,方法filepath.HasPrefix实际上调用了strings.HasPrefix,所以答案是肯定的。

英文:

In Go 1.4 method filepath.HasPrefix actually calls strings.HasPrefix so the answer is yes.

huangapple
  • 本文由 发表于 2015年3月23日 22:56:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/29213429.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定