Go language file operation method
- 2020-05-17 05:40:23
- OfStack
This article illustrates an example of how to manipulate files in the Go language. Share with you for your reference. The details are as follows:
Close file:
func (file *File) Close() os.Error {
if file == nil {
return os.EINVAL
}
e := syscall.Close(file.fd)
file.fd = -1 // so it can't be closed again
if e != 0 {
return os.Errno(e)
}
return nil
}
File reading:
func (file *File) Read(b []byte) (ret int, err os.Error) {
if file == nil {
return -1, os.EINVAL
}
r, e := syscall.Read(file.fd, b)
if e != 0 {
err = os.Errno(e)
}
return int(r), err
}
Write file:
func (file *File) Write(b []byte) (ret int, err os.Error) {
if file == nil {
return -1, os.EINVAL
}
r, e := syscall.Write(file.fd, b)
if e != 0 {
err = os.Errno(e)
}
return int(r), err
}
Get file name:
func (file *File) String() string {
return file.name
}
I hope this article has helped you with your Go language programming.