Skip to content

Instantly share code, notes, and snippets.

@jcarley
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcarley/9649240 to your computer and use it in GitHub Desktop.
Save jcarley/9649240 to your computer and use it in GitHub Desktop.
How to copy chunks from one file to another using Go
package main
// source = http://stackoverflow.com/questions/1821811/how-to-read-write-from-to-file
import (
"bufio"
"io"
"os"
)
func main() {
// open input file
fi, err := os.Open("input.txt")
if err != nil { panic(err) }
// close fi on exit and check for its returned error
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
// make a read buffer
r := bufio.NewReader(fi)
// open output file
fo, err := os.Create("output.txt")
if err != nil { panic(err) }
// close fo on exit and check for its returned error
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// make a write buffer
w := bufio.NewWriter(fo)
// make a buffer to keep chunks that are read
buf := make([]byte, 1024)
for {
// read a chunk
n, err := r.Read(buf)
if err != nil && err != io.EOF { panic(err) }
if n == 0 { break }
// write a chunk
if _, err := w.Write(buf[:n]); err != nil {
panic(err)
}
}
if err = w.Flush(); err != nil { panic(err) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment