Created
November 26, 2019 22:24
-
-
Save FMRb/deb1ee637aede978c8501ad6ccc6413c to your computer and use it in GitHub Desktop.
Creating, reading and writing a file in Golang
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 | |
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