Golang : Read file with ioutil
This tutorial will show you how to read a file into buffer and display the content in Go. This example read plain text file, if you are reading a binary file... change fmt.Println(string(file))
to fmt.Println(file)
(without the string).
Reading binary file will be more tricky as you need to know the format before reading the file. It will be covered in another tutorial.
For now, this is the most basic example of reading a file in Go with io/ioutil
readfileioutil.go
package main
import (
"fmt"
"io/ioutil"
)
func main() {
file, err := ioutil.ReadFile("testfile.txt")
if err != nil {
fmt.Println(err)
return
}
// out the file content
fmt.Println(string(file))
}
See also : Golang : Read file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+3.8k Facebook : How to place save to Facebook button on your website
+23.5k Golang : Create PDF file from HTML file
+11.2k Golang : convert(cast) string to integer value
+11.5k Golang : HTTP response JSON encoded data
+4.8k List of Golang XML tutorials
+5.3k Golang : How to solve "too many .rsrc sections" error?
+28.4k Golang : Get and Set User-Agent examples
+13k Golang : Convert IP version 6 address to integer or decimal number
+13.2k Golang : GUI with Qt and OpenCV to capture image from camera
+3.8k JavaScript: Add marker function on Google Map
+2.3k Golang : Switch Redis database redis.NewClient
+5.8k Golang : Muxing with Martini example