📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Read file to string given filepath

Golang: Read file line by line and return string.

import (
    "os"
    "bufio"
)

func ReadFileToString(filename string) {
	fs, err := os.Open(filename)
	if err != nil {
		log.Fatalf("Failed to open file %s\n", filename)
	}
	defer fs.Close()
	scanner := bufio.NewScanner(fs)
	var data string
	for scanner.Scan() {
		data += scanner.Text() + "\n"
	}
    return data
}

Or if you want to use shorter version.

import (
	"op/ioutil"
	"log"
	"fmt"
)

func main() {
    result, err := ioutil.ReadFile("thermopylae.txt")
	if err != nil {
		log.Fatal(err)
	}

    fmt.Println(string(result))
}

For scaning string word by word.

import (
    "fmt"
    "os"
    "bufio"
)

func main() {
    file, err := os.Open("thermopylae.txt")
    if err != nil {
		fmt.Println(err)
	}

    defer file.Close()

    scanner := bufio.NewScanner(file)
    scanner.Split(bufio.ScanWords)

    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        fmt.Println(err)
    }
}