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
+12.5k Golang : Tutorial on loading GOB and PEM files
+10.4k Golang : Byte format example
+7.9k Golang : How to extract video or image files from html source code
+12.9k Golang : Check if a file exist or not
+11.3k Golang : Arithmetic operation with numerical slices or arrays example
+13.3k Golang : Convert(cast) int to float example
+4.3k Golang : How to deal with configuration data?
+13.6k Golang : Accurate and reliable decimal calculations
+8.3k Golang : Find correlation coefficient example
+50.1k Golang : Check if item is in slice/array
+18.8k Golang : Read directory content with os.Open
+27.8k Golang : Save map/struct to JSON or XML file