golang: cross platform path.Dir

前端 未结 1 1809
执笔经年
执笔经年 2021-02-20 08:13

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         


        
相关标签:
1条回答
  • 2021-02-20 08:44

    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
    
    0 讨论(0)
提交回复
热议问题