Reading the file into a string
In the previous recipes, we saw the reading from Stdin
and the opening of the file. In this recipe, we will combine these two a little bit and show how to read the file into a string.
How to do it...
- Open the console and create the folder
chapter05/recipe04
. - Navigate to the directory.
- Create the directory
temp
and create the filefile.txt
in it. - Edit the
file.txt
file and write multiple lines into the file.
- Create the
readfile.go
file with the following content:
package main import "os" import "bufio" import "bytes" import "fmt" import "io/ioutil" func main() { fmt.Println("### Read as reader ###") f, err := os.Open("temp/file.txt") if err != nil { panic(err) } defer f.Close() // Read the // file with reader wr := bytes.Buffer{} sc := bufio.NewScanner(f) for sc.Scan() { wr.WriteString...