如何正确实例化os.FileMode [英] How to properly instantiate os.FileMode

查看:89
本文介绍了如何正确实例化os.FileMode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过无数的示例和教程,这些示例和教程展示了如何通过仅设置文件的权限位来创建文件,并且所有这些文件都作弊".我想知道/找出如何在创建/更新文件的过程中正确实例化os.FileMode以提供给编写者.

I have seen countless examples and tutorials that show how to create a file and all of them "cheat" by just setting the permission bits of the file. I would like to know / find out how to properly instantiate os.FileMode to provide to a writer during creation / updating of a file.

下面是一个简单的例子:

A crude example is this below:

func FileWrite(path string, r io.Reader, uid, gid int, perms string) (int64, error){
    w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0664)
    if err != nil {
        if path == "" {
            w = os.Stdout
        } else {
            return 0, err
        }
    }
    defer w.Close()

    size, err := io.Copy(w, r)

    if err != nil {
        return 0, err
    }
    return size, err
}

在上面的基本功能中,设置了权限位0664,尽管有时这很有意义,但我有时还是希望有一种正确设置文件模式的正确方法.如上所示,一个常见的示例是UID/GID是已知的,并且已经作为int值提供了,而perms是八进制数字,以前已将其收集并作为字符串插入到db中.

In the basic function above permission bits 0664 is set and although this may make sense sometimes I prefer to have a proper way of setting the filemode correctly. As seen above a common example would be that the UID / GID is known and already provided as int values and the perms being octal digits that were previously gathered and inserted into a db as a string.

推荐答案

FileMode只是一个uint32. http://golang.org/pkg/os/#FileMode

FileMode is just a uint32. http://golang.org/pkg/os/#FileMode

通过常量设置不是欺骗",您可以像使用其他数值一样使用它.如果您不使用常量,则可以对有效的数值进行转换:

Setting via constants isn't "cheating", you use it like other numeric values. If you're not using a constant, you can use a conversion on valid numeric values:

mode := int(0777)
os.FileMode(mode)

这篇关于如何正确实例化os.FileMode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆