在 Golang 中,WriteAt 函数是用于向指定偏移量写入数据的函数。其函数签名如下:
func (file *File) WriteAt(b []byte, off int64) (n int, err error)
其中,file 表示要写入的文件,b 表示要写入的数据,off 表示数据在文件中的偏移量。函数返回值 n 表示实际写入的字节数,err 表示写入过程中发生的错误。
使用示例:
package main
import (
"os"
)
func main() {
// 打开文件
file, err := os.OpenFile("test.txt", os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
panic(err)
}
defer file.Close()
// 写入数据到偏移量为 4 的位置
n, err := file.WriteAt([]byte("hello"), 4)
if err != nil {
panic(err)
}
println(n)
}
以上代码打开文件 "test.txt",然后向偏移量为 4 的位置写入了字符串 "hello"。




