Standard library / os
os.File.WriteAt()
Writes bytes at a specified offset without changing the sequential cursor; rejects append-mode files. Example uses a disposable temporary workspace. Expected stdout: '1 aXc\n'.
Formal Syntax & Structure
go syntaxgo
func (f *File) WriteAt(b []byte, off int64) (n int, err error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| b | []byte | Byte buffer for reading or writing. |
| off | int64 | Explicit byte offset. |
Return Value
(n int, err error)
Writes bytes at a specified offset without changing the sequential cursor; rejects append-mode files.
Working Example
Example Snippetgo
package main
import ( "fmt" "os")
func check(e error) { if e != nil { panic(e) }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func opened() *os.File { seed(); f, e := os.OpenFile("a.txt", os.O_RDWR, 0); check(e); return f }func workspace() func() { root, e := os.MkdirTemp("", "bytemind-go-") check(e) old, e := os.Getwd() check(e) check(os.Chdir(root)) return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() { defer workspace()() f := opened() defer f.Close() n, e := f.WriteAt([]byte("X"), 1) check(e) b, e := os.ReadFile("a.txt") check(e) fmt.Println(n, string(b))}