Skip to content

Instantly share code, notes, and snippets.

@fasterthanlime
Last active December 31, 2016 15:26
Show Gist options
  • Save fasterthanlime/b4fc0275f2495b8999a3cd4d3dd82ec5 to your computer and use it in GitHub Desktop.
Save fasterthanlime/b4fc0275f2495b8999a3cd4d3dd82ec5 to your computer and use it in GitHub Desktop.
TIL: it's possible to open the same path twice (even on Windows!) - it might not be a good idea, though.
package main
import (
"io/ioutil"
"log"
"os"
)
func main() {
path := "sample.txt"
weirdWrites(path)
read(path)
}
func weirdWrites(path string) {
f1, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
f2, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
log.Fatal(err)
}
_, err = f1.Write([]byte("one"))
if err != nil {
log.Fatal(err)
}
_, err = f2.Write([]byte("two two"))
if err != nil {
log.Fatal(err)
}
err = f2.Close()
if err != nil {
log.Fatal(err)
}
_, err = f1.Write([]byte("extra one"))
if err != nil {
log.Fatal(err)
}
err = f1.Close()
if err != nil {
log.Fatal(err)
}
}
func read(path string) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
log.Print(string(bytes))
}
2016/12/31 16:24:44 twoextra one
2016/12/31 15:25:46 twoextra one
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment