上QQ阅读APP看书,第一时间看更新
File modes
We saw that the os.OpenFile function makes it possible to choose how to open a file with the file mode, which is a uint32 where each bit has a meaning (like Unix files and folder permissions). The os package offers a series of values, each one specifying a mode, and the correct way to combine them is with | (bitwise OR).
The following code shows the ones that are available, and have been taken directly from Go's source:
// 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 // if possible, truncate file when opened.
The first three represent the operation that's allowed (read, write, or both), and the others are as follows:
- O_APPEND: Before each write, the file offset is positioned at the end of the file.
- O_CREATE: Makes it possible to create the file if it doesn't exist.
- O_EXCL: If this is used with create, it fails if the file already exists (exclusive creation).
- O_SYNC: Executes a read/write operation and verifies its competition.
- O_TRUNC: If the file exists, its size is truncated to 0.