forked from hantmac/Mastering_Go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
#**文件权限** | ||
|
||
`Unix`系统编程中的一个热门话题是`Unix`文件权限。在本节中,假设你有足够的`Unix`权限,你将学习如何输出任意文件的权限!程序名为`permission.go`,分为三部分。 | ||
|
||
`permission.go`的第一部分代码如下: | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"os" | ||
) | ||
``` | ||
|
||
`permission.go`的第二部分代码如下: | ||
|
||
```go | ||
func main() { | ||
arguments := os.Args | ||
if len(arguments) == 1 { | ||
fmt.Printf("usage:permissions filename\n") | ||
return | ||
} | ||
``` | ||
最后一部分代码如下: | ||
```go | ||
filename := arguments[1] | ||
info, _ := os.Stat(filename) | ||
mode := info.Mode() | ||
fmt.Println(filename, "mode is", mode.String()[1:10]) | ||
} | ||
``` | ||
|
||
`os.Stat(filename)`调用返回一个大结构体,其中包含了许多数据。因为我们只对文件的权限感兴趣,我们调用`Mode()`方式并打印输出。实际上,我们通过`mode.String()[1:10]`打印了输出的一部分,因为它即是我们感兴趣的那部分。 | ||
|
||
执行`permission.go`将产生如下输出: | ||
|
||
```shell | ||
$ go run permission.go /tmp/adobegc.log | ||
/tmp/adobegc.log mode is rw-rw-rw- | ||
$ go run permissions.go /dev/random | ||
/dev/random mode is crw-rw-rw | ||
``` | ||
|
||
`ls(1)`输出可以验证`permission.go`的正确性: | ||
|
||
```shel | ||
$ ls -l /dev/random /tmp/adobegc.log | ||
crw-rw-rw- 1 root wheel 14, 0 Jan 8 20:24 /dev/random | ||
-rw-rw-rw- 1 root wheel 583454 Jan 16 19:12 /tmp/adobegc.log | ||
``` | ||
|