Go语言编程中对文件读写的基本方法整理

2019-11-10 10:03:03刘景俊

 }
 p := make([]byte, 10)
 var total int
 for {
  n, err := limitedreader.Read(p)
  if err == io.EOF {
   fmt.Println("read total", total)     //read total 11
   fmt.Println("read value", string(p)) //read value hello widuu
   break
  }
  total = total + n

 }

}


7.type PipeReader


type PipeReader struct {
    // contains filtered or unexported fields
}


(1)func Pipe() (*PipeReader, *PipeWriter)创建一个管道,并返回它的读取器和写入器,这个会在内存中进行管道同步,它的开启会io.Reader然后等待io.Writer的输入,没有内部缓冲,它是安全的调用Read和Write彼此和并行调用写


import (
 "fmt"
 "io"
 "reflect"
)

func main() {
 r, w := io.Pipe()
 fmt.Println(reflect.TypeOf(r)) //*io.PipeReader
 fmt.Println(reflect.TypeOf(w)) //*io.PipeWriter
}


(2)func (r *PipeReader) Close() error管道关闭后,正在进行或后续的写入Write操作返回ErrClosedPipe

import (
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 r.Close()

 _, err := w.Write([]byte("hello widuu")) 

 if err == io.ErrClosedPipe {
  fmt.Println("管道已经关闭无法写入") //管道已经关闭无法写入
 }
}


(3)func (r *PipeReader) CloseWithError(err error) error这个就是上边的r.Close关闭的时候,写入器会返回错误的信息


import (
 "errors"
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 r.Close()
 err := errors.New("管道符关闭了") //errors这个包我们前边已经说过了,就一个方法New不会的可以看看前边的
 r.CloseWithError(err)
 _, err = w.Write([]byte("test"))
 if err != nil {
  fmt.Println(err) //管道符关闭了
 }
}


(4)func (r *PipeReader) Read(data []byte) (n int, err error)标准的阅读接口,它从管道中读取数据、阻塞一直到一个写入接口关闭,如果写入端发生错误,它就会返回错误,否则返回的EOF


import (
 "fmt"
 "io"
)

func main() {
 r, w := io.Pipe()
 go w.Write([]byte("hello widuu"))
 d := make([]byte, 11)
 n, _ := r.Read(d) //从管道里读取数据
 fmt.Println(string(d))
 fmt.Println(n)
}