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
+16k Golang : Simple client server example
+15.6k Golang : Upload/Receive file progress indicator
+21.7k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+7.3k Golang : Handle sub domain with Gin
+30.3k Golang : Regular Expression for alphanumeric and underscore
+8.1k Golang : Check if user agent is a robot or crawler example
+9.3k Use systeminfo to find out installed Windows Hotfix(s) or updates
+4.2k Golang : What is StructTag and how to get StructTag's value?
+10.7k Golang : Validate email address
+6.8k Golang : Ackermann function example
+7.4k Golang : Find duplicate files with filepath.Walk
+20.4k Golang : Test file read write permission example