This article analyzes the creation and opening usage of GO language files. Share it for your reference. The specific analysis is as follows:
File operation is a very important topic and is used very frequently. It is essential to be familiar with how to operate files. Golang's support for files is in the os package, and the specific operations are encapsulated in the type File struct {} structure.
1. func Open(name string) (file *File, err error)
It couldn't be easier. Give it a path and return the file descriptor. If an error occurs, it will return a *PathError.
This is a read-only opening mode, which is actually a quick operation of (). Its prototype is as follows:
return OpenFile(name, O_RDONLY, 0)
}
2. func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
This complex point requires providing file path, opening mode, and file permissions.
Open the tag:
O_RDONLY: read-only mode (read-only)
O_WRONLY: write-only mode
O_RDWR: read-write mode (read-write)
O_APPEND: Append mode (append)
O_CREATE: Create a new file if none exists.)
O_EXCL: Used with O_CREATE to form a new file function, it requires that the file must not exist (used with O_CREATE, file must not exist)
O_SYNC: Open synchronously, that is, do not use cache, and write directly to the hard disk
O_TRUNC: Open and clear the file
File permissions (unix permission bit): Only required when creating a file, if you do not need to create a file, you can set it to 0. Although the os library provides constants, I usually write numbers directly, such as 0664.
If you need to set multiple open tags and unix permission bits, you need to use the bit operator "|", the sample code is as follows:
if err != nil {
panic(err)
}
If the file exists, it will be opened in read-write mode and appended; if the file does not exist, it will be created and then opened in read-write mode.
3. func Create(name string) (file *File, err error)
In fact, this is also a quick operation of (). Create a new file and open it in read and write mode, with permission bit "0666", and will be cleared if the file exists. The prototype is as follows:
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
4. Please remember to release any file in time.
f, err := (pth)
if err!=nil{
return err
}
defer () //Release resources and never forget them
...
}
There is also a func NewFile(fd uintptr, name string) *File function in the os module, which creates a file using the given Unix file descriptor and name. refer to:
Stdout = NewFile(uintptr(), "/dev/stdout")
Stderr = NewFile(uintptr(), "/dev/stderr")
I hope this article will be helpful to everyone's GO language programming.