WriteAt Patches Bytes At Offsets
Write into fixed regions of a file with os.File.WriteAt: disjoint offsets compose independently and a later patch rewrites only the targeted byte range.
Code
package main
import (
"fmt"
"os"
)
func main() {
sector, err := os.CreateTemp("", "sector-*.bin")
if err != nil {
fmt.Println("create:", err)
return
}
name := sector.Name()
sector.Close()
defer os.Remove(name)
file, err := os.OpenFile(name, os.O_RDWR, 0o644)
if err != nil {
fmt.Println("open:", err)
return
}
defer file.Close()
// WriteAt 按绝对偏移写:两段不重叠,写入顺序不影响最终布局
if _, err := file.WriteAt([]byte("beta"), 8); err != nil {
fmt.Println("write:", err)
return
}
if _, err := file.WriteAt([]byte("alpha"), 0); err != nil {
fmt.Println("write:", err)
return
}
data, err := os.ReadFile(name)
if err != nil {
fmt.Println("read:", err)
return
}
fmt.Printf("content: %q\n", data)
// 覆盖中间一段:只影响目标区间,其余字节保持原样
if _, err := file.WriteAt([]byte("BETA"), 8); err != nil {
fmt.Println("write:", err)
return
}
patched, _ := os.ReadFile(name)
fmt.Printf("patched: %q\n", patched)
}Walkthrough
All of the logic sits inside the function main.
err is inspected at 6 call sites before any result is trusted. Cleanup is attached with defer, so it runs on every exit path of the function.
Caveats
- Zero installs — the standard library is all it touches.
Applying it
The entry-point signature is func main()
The file’s steps show up in the output as create:, open:, write:.
Statements that matter
if err != nil {
fmt.Println("create:", err)
return
}
if err != nil {
fmt.Println("open:", err)
return
}
if err != nil {
fmt.Println("read:", err)
return
}
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does WriteAt Patches Bytes At Offsets print when run?
- Invoke the file as-is — the `create:`, `open:`, `write:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.