英文:
golang: cross platform path.Dir
问题
我想在Unix和Windows上使用path.Dir()
来处理特定于平台的目录。请看一下代码:
package main
import (
"fmt"
"path"
)
func main() {
fmt.Println(`path.Dir("a/b/c"): `, path.Dir("a/b/c"))
fmt.Println(`path.Dir("c:\foo\bar.exe"): `, path.Dir(`c:\foo\bar.exe`))
}
这将输出:
path.Dir("a/b/c"): a/b
path.Dir("c:\foo\bar.exe"): .
我想在第二次调用path.Dir()
(Windows)时获得类似于
c:\foo
的结果。是否可以告诉path.Dir()
在Windows上使用Windows分隔符?或者我应该始终将反斜杠\
转换为正斜杠(/
)?这里有什么首选策略吗?
英文:
I'd like to use path.Dir()
on Unix and Windows with a platform specific directory. Please take a look at the code:
package main
import (
"fmt"
"path"
)
func main() {
fmt.Println(`path.Dir("a/b/c"): `, path.Dir("a/b/c"))
fmt.Println(`path.Dir("c:\foo\bar.exe"): `, path.Dir(`c:\foo\bar.exe`))
}
This outputs
path.Dir("a/b/c"): a/b
path.Dir("c:\foo\bar.exe"): .
I'd like to get for the second call to path.Dir()
(windows) something like
c:\foo
Is it possible to tell path.dir()
to use Windows separators for my program running on windows? Or should I always convert the backslashes \
to forward slashes (/
)? What is the preferred strategy here?
答案1
得分: 16
我看到了“问题”的所在。这个在golang-nuts上的讨论给了我一个提示,即path.Dir()
总是使用/
,而filepath.Dir()
是用于平台相关操作的函数。
package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Println(`filepath.Dir("a/b/c"): `, filepath.Dir("a/b/c"))
fmt.Println(`filepath.Dir("c:\foo\bar.exe"): `, filepath.Dir(`c:\foo\bar.exe`))
}
在Windows上:
filepath.Dir("a/b/c"): a\b
filepath.Dir("c:\foo\bar.exe"): c:\foo
英文:
I see where the "problem" is. This discussion at golang-nuts gave me the hint, that path.Dir()
always uses /
and filepath.Dir()
is the function to be used for platform dependent manipulation.
package main
import (
"fmt"
"path/filepath"
)
func main() {
fmt.Println(`filepath.Dir("a/b/c"): `, filepath.Dir("a/b/c"))
fmt.Println(`filepath.Dir("c:\foo\bar.exe"): `, filepath.Dir(`c:\foo\bar.exe`))
}
on windows:
filepath.Dir("a/b/c"): a\b
filepath.Dir("c:\foo\bar.exe"): c:\foo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论