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
+7.5k Golang : get the current working directory of a running program
+6.6k Nginx : Password protect a directory/folder
+13k Golang : Linear algebra and matrix calculation example
+9.8k Golang : Channels and buffered channels examples
+9.6k Golang : Get current, epoch time and display by year, month and day
+15.2k Golang : rune literal not terminated error
+9.5k Golang : Qt get screen resolution and display on center example
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+21.3k Golang : GORM create record or insert new record into database example
+12.9k Golang : How to get a user home directory path?
+13.1k Golang : Generate Code128 barcode
+18.1k Golang : Aligning strings to right, left and center with fill example