dongzhouji4021
2019-06-03 20:55
浏览 664
已采纳

golang将os.ModePerm转换为字符串

I would like to have as a string the permissions representation of a file. Here is what I want to do :

fileInfo, err := os.Lstat(path)
fileMode := fileInfo.Mode()
// fileMode.String() gives dturwxrwxrwx or -rwxrwxrwx
// which i do not want because the size is not always the same
unixPerms := fileMode & os.ModePerm

I get -rwxrwxrwx for both cases, which is close to what i am looking for.

However, the returned object is of type os.FileMode. How can I then convert it into a string?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • download92000 2019-06-03 21:03
    已采纳

    You can pass either one of your variables, type (os.FileMode), as an argument to the Sprintf method from the fmt package.

    Leveraging this method will convert your type into a string, which can then be used as a string throughout the remainder of your program.

    Example usage below:

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func main() {
        fileInfo, err := os.Lstat(path)
        if err != nil {
            // catch err
        }
        fileMode := fileInfo.Mode()
        // fileMode.String() gives dturwxrwxrwx or -rwxrwxrwx
        // which i do not want because the size is not always the same
        unixPerms := fileMode & os.ModePerm
    
        permString := fmt.Sprintf("%v", unixPerms)
        fmt.Println(permString)
    }
    
    点赞 评论
  • duanlie2709 2019-06-03 22:45

    fileInfo.Mode().Perm().String()

    https://golang.org/pkg/os/#FileMode.Perm

    点赞 评论

相关推荐 更多相似问题