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
+14.1k Golang : Fix image: unknown format error
+14k Golang : convert rune to unicode hexadecimal value and back to rune character
+26k Mac/Linux and Golang : Fix bind: address already in use error
+7.4k Golang : Create zip/ePub file without compression(use Store algorithm)
+5.8k Cash Flow : 50 days to pay your credit card debt
+7.1k Golang : Get environment variable
+29.7k Golang : Record voice(audio) from microphone to .WAV file
+33.9k Golang : Call a function after some delay(time.Sleep and Tick)
+6.7k Golang : Output or print out JSON stream/encoded data
+18.3k Golang : Read binary file into memory
+25.3k Golang : Get current file path of a file or executable
+14.8k Golang : Find commonalities in two slices or arrays example