文件操作之前,需要先引入os包(import "os"),然后使用os.FunctionName进行相关文件的操作。
文件操作
1、创建文件
func Create(name string) (*File, error)Create creates the named file with mode 0666 (before umask), truncating it if it already exists. 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 NewFile(fd uintptr, name string) *FileNewFile returns a new File with the given file descriptor and name.
2、打开文件
func Open(name string) (*File, error)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 OpenFile(name string, flag int, perm FileMode) (*File, error)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.) and perm, (0666 etc.) if applicable. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.
3、写文件
func (f *File) Write(b []byte) (n int, err error)Write writes len(b) bytes to the File. It returns the number of bytes written and an error, if any. Write returns a non-nil error when n != len(b).
func (f *File) WriteAt(b []byte, off int64) (n int, err error)WriteAt writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any. WriteAt returns a non-nil error when n != len(b).
func (f *File) WriteString(s string) (n int, err error)WriteString is like Write, but writes the contents of string s rather than a slice of bytes.
4、读文件
func (f *File) Read(b []byte) (n int, err error)Read reads up to len(b) bytes from the File. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.
func (f *File) ReadAt(b []byte, off int64) (n int, err error)ReadAt reads len(b) bytes from the File starting at byte offset off. It returns the number of bytes read and the error, if any. ReadAt always returns a non-nil error when n < len(b). At end of file, that error is io.EOF.
5、删除文件
func Remove(name string) errorRemove removes the named file or directory. If there is an error, it will be of type *PathError.