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
+10.6k Golang : Natural string sorting example
+9.1k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+5.6k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+37.1k Upload multiple files with Go
+16.7k Golang : Get input from keyboard
+10.9k Golang : Fix - does not implement sort.Interface (missing Len method)
+8k Golang : Check if integer is power of four example
+10.9k Golang : Intercept and process UNIX signals example
+6.3k Golang : Convert an executable file into []byte example
+9.2k Facebook : Getting the friends list with PHP return JSON format
+7k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+8.9k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)