Featured image by Egon Elbre
- Finishing going through https://golangbot.com/learn-golang-series/
- Continuing to watch some of Golang University 101
Reading files
- Reading the entire file into memory.
import "io/ioutil"
data, err := ioutil.ReadFile("lorem.txt")
if err != nil {
fmt.Println("Failed to read the file. Error: ", err)
return
}
//NOTE: ReadFile returns a byte slice
fmt.Printf("Contents of file:\n%s\n", string(data))
- You can pack static files into the binary using a tool like packr. Might and might not be of use to me in the future.
- Reading a file in chunks using
bufio
package.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
// Open the file
f, err := os.Open("lorem.txt")
if err != nil {
log.Fatal(err)
}
// Ensure the file is closed when we are done
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
// Read from the file (f) into a buffer (b) 128 bytes at a time
r := bufio.NewReader(f)
b := make([]byte, 128)
for {
n, err := r.Read(b)
if err != nil {
fmt.Println("Error reading file:", err)
break
}
fmt.Println(string(b[0:n]))
}
}
- Reading a text file line by line.
s := bufio.NewScanner(f)
for s.Scan() {
fmt.Println(s.Text())
}
// Check if any errors occurred (other than EOF)
err = s.Err()
if err != nil {
log.Fatal(err)
}
Writing files
- Writing strings to a file.
package main
import (
"fmt"
"log"
"os"
)
func main() {
// Create a new file
f, err := os.Create("test.txt")
if err != nil {
log.Fatal(err)
return
}
// Ensure the file is closed when we are done
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
// Write a single string
bc, err := f.WriteString("The quick brown fox ...")
if err != nil {
log.Fatal(err)
return
}
fmt.Println(bc, "bytes written successfully")
}
- Writing bytes to file.
data := []byte{0x41, 0x6E, 0x64, 0x72, 0x65}
bc, err := f.Write(data)
- The
fmt
package also have some nice utility functions likeFPrintf
&FPrintln
- Open a file for appending.
f, err := os.OpenFile("/path/to/file", os.O_APPEND | os.O_WRONLY, 0644)
// Flags are append and "write-only"
// Also passing unix permissions 0644
What’s next?
I will be working through Alex Ellis’ Everyday Golang book.
I already know of at least 2 small little programs that I want to write that deals with my Linux server and to help me organise some of my data. More details will follow once I actually write the apps.