GO语言的IO方法实例小结

2019-11-10 10:32:26王冬梅

 fmt.Println(string(p[:n])) //hello widu
}


type SectionReader{}


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


(1)func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader,你一看就知道了,其实就是通过这个方法获取到io.SectionReader,第一个参数读取器,第二个参数偏移量,第三个参数是读取多少

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

func main() {
 f, _ := os.Open("test.txt")
 sr := io.NewSectionReader(f, 2, 5)
 fmt.Println(reflect.TypeOf(sr)) //*io.SectionReader
}

(2)func (s *SectionReader) Read(p []byte) (n int, err error)熟悉的read()其实就是读取数据用的,大家看函数就可以理解了,因为咱们经常遇到这个上两个都写这个了~~

import (
 "fmt"
 "io"
 "os"
)

func main() {
 f, _ := os.Open("test.txt")
 defer f.Close()
 sr := io.NewSectionReader(f, 2, 5)
 p := make([]byte, 10)
 n, err := sr.Read(p)
 if err != nil {
  fmt.Println(err)
 }
 fmt.Println(string(p[:n])) //llo w
}

(3)func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)额这个跟之前的ReadAt是一样的,只不过只有一个偏移量,少了截取数,但是你要知道SectionReader做的是什么就把数据截取了,所以就不需要截取数了

import (
 "fmt"
 "io"
 "os"
)

func main() {
 f, _ := os.Open("test.txt")
 defer f.Close()
 sr := io.NewSectionReader(f, 2, 5)
 p := make([]byte, 10)
 n, err := sr.ReadAt(p, 1)
 if err == io.EOF {
  fmt.Println(string(p[:n])) // lo w
 }

}

(4)func (s *SectionReader) Seek(offset int64, whence int) (int64, error)这个是设置文件指针的便宜量的,之前我们的os里边也是有个seek的,对SectionReader的读取起始点、当前读取点、结束点进行偏移,offset 偏移量,whence 设定选项 0:读取起始点,1:当前读取点,2:结束点(不好用),其他:将抛出Seek: invalid whence异常

import (
 "fmt"
 "io"
 "os"
)

func main() {
 f, _ := os.Open("test.txt")
 defer f.Close()
 sr := io.NewSectionReader(f, 2, 5)
 p := make([]byte, 10)
 sr.Seek(1, 0)      //相当于起始的地址偏移1
 n, err := sr.Read(p)
 if err != nil {
  fmt.Println(err)
 }
 fmt.Println(string(p[:n])) //lo w 是不是达到了前边的ReadAt()