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

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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 提问应符合社区要求 12月14日

悬赏问题

  • ¥15 关于#51单片机#的问题:运算放大电路
  • ¥15 电路原理(关键词-工作原理)
  • ¥15 yolov5s模型下载就卡住,没有运行结果
  • ¥15 请问代码技术们,云梦建站的这个坑你们踩过吗?
  • ¥20 androidstudio工具问题
  • ¥15 想问一些关于计量的问题
  • ¥15 关于c++外部库文件宏的问题,求解
  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2