Standard library / os
os.File.WriteTo()
Copies from the open file to a writer, implementing io.WriterTo; count is bytes copied. Example uses a disposable temporary workspace. Expected stdout: '3 abc\n'.
Formal Syntax & Structure
go syntaxgo
func (f *File) WriteTo(w io.Writer) (n int64, err error)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| w | io.Writer | Destination writer. |
Return Value
(n int64, err error)
Copies from the open file to a writer, implementing io.WriterTo; count is bytes copied.
Working Example
Example Snippetgo
package main
import ( "bytes" "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() var b bytes.Buffer n, e := f.WriteTo(&b) check(e) fmt.Println(n, b.String())}