Last active
August 29, 2015 13:57
-
-
Save jcarley/9649240 to your computer and use it in GitHub Desktop.
How to copy chunks from one file to another using Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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