Standard library / os

os.File.ReadFrom()

Copies from a reader into the open file; implements io.ReaderFrom, returning bytes copied and any error. Example uses a disposable temporary workspace. Expected stdout: '2\n'.

Formal Syntax & Structure

go syntaxgo
func (f *File) ReadFrom(r io.Reader) (n int64, err error)

Parameters & Attributes

NameTypeDescription
rio.ReaderSource reader.

Return Value

(n int64, err error)

Copies from a reader into the open file; implements io.ReaderFrom, returning bytes copied and any error.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os"  "strings")
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.ReadFrom(strings.NewReader("XY"))  check(e)  fmt.Println(n)}
Go Reference