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
+7k Golang : Randomize letters from a string example
+5k Fontello : How to load and use fonts?
+11.4k Golang : HTTP response JSON encoded data
+3.8k Python : Find out the variable type and determine the type with simple test
+8.6k Golang : Resumable upload to Google Drive(RESTful) example
+12.2k Golang : reCAPTCHA example
+17.9k Golang : Fix cannot download, $GOPATH not set error
+8.6k Golang : Turn string or text file into slice example
+8k Golang : Go as a script or running go with shebang/hashbang style
+11.2k Golang : Search and extract certain XML data example
+11k Golang : Encrypt and decrypt data with x509 crypto
+17.2k Golang : Send email with attachment