Home >Backend Development >Golang >How do you accurately instantiate `os.FileMode` for file creation and updates in Go?

How do you accurately instantiate `os.FileMode` for file creation and updates in Go?

DDD
DDDOriginal
2024-11-11 05:13:02222browse

How do you accurately instantiate `os.FileMode` for file creation and updates in Go?

Understanding and Instantiating os.FileMode for File Creation and Update

In Go programming, the os.FileMode type represents the file permissions and attributes. However, many examples overlook the proper instantiation of os.FileMode for file creation or modification. This article explores how toinstantiate os.FileMode accurately.

To set the permissions directly, define constants representing the permission bits:

const (
    OS_READ = 04
    OS_WRITE = 02
    OS_EX = 01
    OS_USER_SHIFT = 6
    OS_GROUP_SHIFT = 3
    OS_OTH_SHIFT = 0

    OS_USER_R = OS_READ << OS_USER_SHIFT
    OS_USER_W = OS_WRITE << OS_USER_SHIFT
    OS_USER_X = OS_EX << OS_USER_SHIFT
    OS_USER_RW = OS_USER_R | OS_USER_W
    OS_USER_RWX = OS_USER_RW | OS_USER_X

    OS_GROUP_R = OS_READ << OS_GROUP_SHIFT
    OS_GROUP_W = OS_WRITE << OS_GROUP_SHIFT
    OS_GROUP_X = OS_EX << OS_GROUP_SHIFT
    OS_GROUP_RW = OS_GROUP_R | OS_GROUP_W
    OS_GROUP_RWX = OS_GROUP_RW | OS_GROUP_X

    OS_OTH_R = OS_READ << OS_OTH_SHIFT
    OS_OTH_W = OS_WRITE << OS_OTH_SHIFT
    OS_OTH_X = OS_EX << OS_OTH_SHIFT
    OS_OTH_RW = OS_OTH_R | OS_OTH_W
    OS_OTH_RWX = OS_OTH_RW | OS_OTH_X

    OS_ALL_R = OS_USER_R | OS_GROUP_R | OS_OTH_R
    OS_ALL_W = OS_USER_W | OS_GROUP_W | OS_OTH_W
    OS_ALL_X = OS_USER_X | OS_GROUP_X | OS_OTH_X
    OS_ALL_RW = OS_ALL_R | OS_ALL_W
    OS_ALL_RWX = OS_ALL_RW | OS_GROUP_X
)

Now, you can specify your intended permissions explicitly:

var dir_file_mode os.FileMode
dir_file_mode = os.ModeDir | (OS_USER_RWX | OS_ALL_R)
os.MkdirAll(dir_str, dir_file_mode)

The above is the detailed content of How do you accurately instantiate `os.FileMode` for file creation and updates in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn