linux - 如何使用 Go 在 Linux 中检查文件的权限

标签 linux go

我正在学习 Go,我想做的第一个项目是编写 Linux find shell 程序的替代品。我在不到一个小时的时间内用 python 编写了一个替代品。这是一个更大的挑战。

我遇到的问题是当 filepath.Walk 遍历我的文件系统时,它向屏幕吐出一堆权限被拒绝的消息。 我需要一种在 filepath.Walk 接触文件之前检查文件权限的方法。

最佳答案

go 中,文件权限在 os.FileMode 中定义其中基础类型是 uint32。来自文档:

A FileMode represents a file's mode and permission bits...
...
The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

您可以通过os.Stat 检索FileModeos.LStat返回 FileInfo 的函数,例如

info, err := os.Stat("file/directory name")

那么FileMode可以通过调用info.Mode()获得。要检查权限,请对模式位执行按位操作,例如

//Check 'others' permission
m := info.Mode()
if m&(1<<2) != 0 {
    //other users have read permission
} else {
    //other users don't have read permission
}

如果您使用 filepath.Walk 函数访问目录/文件,因为 WalkFunc(Walk 的第二个参数) 定义为

type WalkFunc func(path string, info os.FileInfo, err error) error

某些路径FileInfo可作为WalkFunc的第二个参数,因此您可以直接使用info检查权限.Mode() 而不是在传递给 filepath.Walk 的闭包或函数体内调用 os.Statos.Lstat

关于linux - 如何使用 Go 在 Linux 中检查文件的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45429210/

相关文章:

linux - 如何检测当前进程中动态库(共享对象)的大小?

Golang TCPConn Gob 通信

linux - C++11线程库是否调用OS API来运行多线程程序?

linux - 编译后无法识别 gcc 7.1 参数

go - GRPC : How to pass value from interceptor to service function

rest - 戈朗 : web service that monitors worker goroutine

go - 如何在不进入子目录的情况下迭代目录

function - 将变量 []interface{} 转换为变量 ...interface{} in go

linux - 无法从测试网站 yii2 swiftmailer 发送邮件

linux - 嵌入式 Linux 中的看门狗定时器 > 60 秒