Skip to content

Instantly share code, notes, and snippets.

@physacco
Last active December 14, 2015 18:09
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 physacco/5127253 to your computer and use it in GitHub Desktop.
Save physacco/5127253 to your computer and use it in GitHub Desktop.
Test basic file operations in go. Copy a file using the package os & io.
package main
import (
"io"
"os"
)
func main() {
// Open a file for reading
// The associated file descriptor has mode O_RDONLY.
fi, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer fi.Close()
// Create creates the named file mode 0666 (before umask),
// truncating it if it already exists.
// The associated file descriptor has mode O_RDWR.
fo, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer fo.Close()
// Make a slice as buffer.
buf := make([]byte, 1024)
for {
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 { // EOF
break
}
if n2, err := fo.Write(buf[:n]); err != nil {
panic(err)
} else if n2 != n {
panic("error in writing")
}
}
}
package main
import (
"io"
"os"
"log"
)
func main () {
// open input stream
r, err := os.Open("input.txt")
if err != nil {
panic(err)
}
defer r.Close()
// open output stream
w, err := os.Create("output.txt")
if err != nil {
panic(err)
}
defer w.Close()
// func Copy(dst Writer, src Reader) (written int64, err error)
// Copy copies from src to dst until either EOF is reached on
// src or an error occurs.
n, err := io.Copy(w, r)
if err != nil {
panic(err)
}
log.Printf("Copied %v bytes\n", n)
}
package main
import (
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("input.txt")
if err != nil { panic(err) }
err = ioutil.WriteFile("output.txt", b, 0644)
if err != nil { panic(err) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment