本文介绍了golang:跨平台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`))
}

这个输出


$ b $

  path.Dir(a / b / c):a / b 
path.Dir(c:\ foo \bar.exe):。

我想要第二次调用 path.Dir( )(windows)类似于

  c:\foo 

是否可以告诉 path.dir()使用Windows分隔符作为我的程序在Windows上运行?或者我应该总是将反斜杠 \ 转换成正斜杠( / )?这里的首选策略是什么?

解决方案

我看到问题在哪里。 给了我一个提示,那就是 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'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?

解决方案

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

这篇关于golang:跨平台path.Dir的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:38