{"id":564,"date":"2022-04-21T10:32:00","date_gmt":"2022-04-21T10:32:00","guid":{"rendered":"https:\/\/andrejacobs.org\/?p=564"},"modified":"2022-04-22T10:35:33","modified_gmt":"2022-04-22T10:35:33","slug":"learning-go-day-5","status":"publish","type":"post","link":"https:\/\/andrejacobs.org\/study-notes\/learning-go-day-5\/","title":{"rendered":"Learning Go – Day 5"},"content":{"rendered":"\n
Featured image by\u00a0Egon Elbre<\/a><\/p>\n\n\n\n I will be working through Alex Ellis\u2019 Everyday Golang<\/a> book.<\/p>\n 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.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":" Featured image by\u00a0Egon Elbre […]<\/p>\n\n
\n
Reading files<\/h3>\n
\n
import "io\/ioutil"\n\ndata, err := ioutil.ReadFile("lorem.txt")\nif err != nil {\n\tfmt.Println("Failed to read the file. Error: ", err)\n\treturn\n}\n\/\/NOTE: ReadFile returns a byte slice\nfmt.Printf("Contents of file:\\n%s\\n", string(data))\n<\/code><\/pre>\n
\n
bufio<\/code> package.<\/li>\n<\/ul>\n
package main\n\nimport (\n\t"bufio"\n\t"fmt"\n\t"log"\n\t"os"\n)\n\nfunc main() {\n\t\/\/ Open the file\n\tf, err := os.Open("lorem.txt")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ Ensure the file is closed when we are done\n\tdefer func() {\n\t\tif err = f.Close(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n\t\/\/ Read from the file (f) into a buffer (b) 128 bytes at a time\n\tr := bufio.NewReader(f)\n\tb := make([]byte, 128)\n\tfor {\n\t\tn, err := r.Read(b)\n\t\tif err != nil {\n\t\t\tfmt.Println("Error reading file:", err)\n\t\t\tbreak\n\t\t}\n\t\tfmt.Println(string(b[0:n]))\n\t}\n}\n<\/code><\/pre>\n
\n
s := bufio.NewScanner(f)\nfor s.Scan() {\n fmt.Println(s.Text())\n}\n\/\/ Check if any errors occurred (other than EOF)\nerr = s.Err()\nif err != nil {\n log.Fatal(err)\n}\n<\/code><\/pre>\n
Writing files<\/h3>\n
\n
package main\n\nimport (\n\t"fmt"\n\t"log"\n\t"os"\n)\n\nfunc main() {\n\t\/\/ Create a new file\n\tf, err := os.Create("test.txt")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\t\/\/ Ensure the file is closed when we are done\n\tdefer func() {\n\t\tif err = f.Close(); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}()\n\n \/\/ Write a single string\n\tbc, err := f.WriteString("The quick brown fox ...")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tfmt.Println(bc, "bytes written successfully")\n}\n<\/code><\/pre>\n
\n
data := []byte{0x41, 0x6E, 0x64, 0x72, 0x65}\nbc, err := f.Write(data)\n<\/code><\/pre>\n
\n
fmt<\/code> package also have some nice utility functions like
FPrintf<\/code> &
FPrintln<\/code><\/li>\n
f, err := os.OpenFile("\/path\/to\/file", os.O_APPEND | os.O_WRONLY, 0644)\n\/\/ Flags are append and "write-only"\n\/\/ Also passing unix permissions 0644\n<\/code><\/pre>\n
What\u2019s next?<\/h3>\n