我正在学习 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
检索FileMode
或 os.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.Stat
或 os.Lstat
。
关于linux - 如何使用 Go 在 Linux 中检查文件的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45429210/