os.OpenFile()

1
2
3
4
5
6
7
// Open opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode O_RDONLY.
// If there is an error, it will be of type *PathError.
func Open(name string) (*File, error) {
return OpenFile(name, O_RDONLY, 0)
}

os.Create()

1
2
3
4
5
6
7
8
// Create creates or truncates the named file. If the file already exists,
// it is truncated. If the file does not exist, it is created with mode 0666
// (before umask). If successful, methods on the returned File can
// be used for I/O; the associated file descriptor has mode O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}

os.Open()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// OpenFile is the generalized open call; most users will use Open
// or Create instead. It opens the named file with specified flag
// (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
// is passed, it is created with mode perm (before umask). If successful,
// methods on the returned File can be used for I/O.
// If there is an error, it will be of type *PathError.
func OpenFile(name string, flag int, perm FileMode) (*File, error) {
testlog.Open(name)
f, err := openFileNolog(name, flag, perm)
if err != nil {
return nil, err
}
f.appendMode = flag&O_APPEND != 0

return f, nil
}

flag

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Flags to OpenFile wrapping those of the underlying system. Not all
// flags may be implemented on a given system.
const (
// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
// The remaining values may be or'ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // truncate regular writable file when opened.
)

perm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
一般都文件属性标识如下: 

-rwxrwxrwx

第1位:文件属性,一般常用的是"-",表示是普通文件;"d"表示是一个目录。

第2~4位:文件所有者的权限rwx (可读/可写/可执行)。

第5~7位:文件所属用户组的权限rwx (可读/可写/可执行)。

第8~10位:其他人的权限rwx (可读/可写/可执行)。

 

在golang中,可以使用os.FileMode(perm).String()来查看权限标识:

os.FileMode(0777).String()    //返回 -rwxrwxrwx

os.FileMode(0666).String()   //返回 -rw-rw-rw-

os.FileMode(0644).String()   //返回 -rw-r--r--

注意,golang中创建文件指定权限时,只能以"0XXX"的形式,不能省掉前面的"0",否则指定的权限不是预期的