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
+5k Golang : Issue HTTP commands to server and port example
+9.5k Golang : List available AWS regions
+16.8k Golang : How to save log messages to file?
+9.4k Golang : Validate IPv6 example
+16.1k Golang : Test floating point numbers not-a-number and infinite example
+5.9k PageSpeed : Clear or flush cache on web server
+9.9k Golang : Test a slice of integers for odd and even numbers
+24.2k Golang : Time slice or date sort and reverse sort example
+6.1k Golang : Test input string for unicode example
+7.6k Golang : Lock executable to a specific machine with unique hash of the machine
+26.5k Golang : How to check if a connection to database is still alive ?
+7.6k Golang : Trim everything onward after a word