Skip to content

Instantly share code, notes, and snippets.

@FMRb
Created November 26, 2019 22:24
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 FMRb/deb1ee637aede978c8501ad6ccc6413c to your computer and use it in GitHub Desktop.
Save FMRb/deb1ee637aede978c8501ad6ccc6413c to your computer and use it in GitHub Desktop.
Creating, reading and writing a file in Golang
package main
import (
"io"
"log"
"os"
)
func main() {
file, err := os.OpenFile("text.txt",
os.O_RDWR|os.O_CREATE,
0666,
)
if err != nil {
log.Fatalf("Error openFile: %v", err)
}
defer file.Close()
readByteSlice := make([]byte, 16)
bytesRead, err := file.Read(readByteSlice)
if err != nil && err != io.EOF {
log.Fatalf("Error reading file: %v", err)
}
log.Printf("Number of bytes read: %d\n", bytesRead)
log.Printf("Data read: %s\n", readByteSlice)
byteSlice := []byte("Bytes!\n")
bytesWritten, err := file.Write(byteSlice)
if err != nil {
log.Fatalf("Error writting file: %v", err)
}
log.Printf("Wrote %d bytes. \n", bytesWritten)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment