Seeker接口使用

Seeker接口

type Seeker interface {
    Seek(offset int64, whence int) (int64, error)
}

这里的Seek()方法将移动当前读写位置到offset、whence表示的偏移处 offset是相对于whence的偏移量
其中 whence有三种值
- io.SeekStart:相对于文件起始位置
- io.SeekCurrent:相对于文件当前位置
- io.SeekEnd:相对于文件末尾

示例

package main

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

// seek接口
func main() {
	file, err := os.OpenFile("F:\\20_environment\\04_go_works\\src\\lesson11\\a.txt", os.O_RDWR, os.ModePerm)
	if err != nil {
		fmt.Println("读取出错啦", err)
		return
	}

	defer file.Close()

	// 相对于开始位置 偏移2个位置
	file.Seek(2, io.SeekStart)
	buf := []byte{0, 1}
	file.Read(buf)

	// 开始的光标在a前面 由于偏移了两个  直接到c前面了 顾从c开始读取两个字节的数据
	fmt.Println(string(buf)) // cd

	// 相对于当前位置偏移  此时光标的位置在e前面  偏移了2个  到了g前面
	file.Seek(2, io.SeekCurrent)
	file.Read(buf)
	fmt.Println(string(buf)) // gh

	// 在结尾添加数据
	file.Seek(0, io.SeekEnd)
	file.WriteString("123456")
}

a.txt文件内容

abcdefghijklmnopqrstuvwxyz
posted @ 2023-05-18 13:58  晚秋时节  阅读(70)  评论(0)    收藏  举报