golang IO

IO follicles

io.Reader

type Reader interface {
    Read(p []byte) (n int, err error)
}
  • Any type implements the Read method have achieved io.Reader Interface
  • Can be read from the Reader interface fetch the data to the p
  • After successfully read n> 0 bytes, if an error is encountered or the end of file returns an error
    • So when n> 0, the process should first read data, these data are valid
// 文件拷贝
func CopyFile(dstName, srcName string) (written int64, err error) {
	src, err := os.Open(srcName)
	if err != nil {
		return
	}
	defer src.Close()

	dst, err := os.Create(dstName)
	if err != nil {
		return
	}
	defer dst.Close()

	return io.Copy(dst, src)
}

io.Writer

type Writer interface {
    Write(p []byte) (n int, err error)
}
  • Any type implements the Write method of the interface are implemented io.Writer
  • You can write to the Writer interface into the data p
  • os.Stdout, os.Stderr so achieve io.Writer Interface

OS package

// 只读打开文件
os.Open(name string) (*File, error)
// 打开文件
os.OpenFile(name string, flag int, perm FileMode) (*File, error)
  • flag possible values
    • os.O_RDONLY: Read-only
    • os.O_WRONLY:just write
    • os.O_CREATE: Create: If the specified file does not exist, create the file.
    • os.O_TRUNC: Truncated: If the specified file already exists, it is truncated to the length of the file 0
  • generally the perm 0666

bufio package

  • IO buffer zone
bufio.NewReader(r io.Reader) *Reader
bufio.NewWriter(w io.Writer) *Writer

ioutil package

Published 161 original articles · won praise 19 · views 50000 +

Guess you like

Origin blog.csdn.net/winter_wu_1998/article/details/102751961