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
+12.5k Golang : Activate web camera and broadcast out base64 encoded images
+12.9k Golang : Check if a file exist or not
+33.1k Golang : Integer is between a range
+6.8k Golang : Error reading timestamp with GORM or SQL driver
+37.9k Golang : How to iterate over a []string(array)
+7.8k Yum Error: no such table: packages
+5.3k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+6.5k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+3.3k Javascript : Empty an array example
+17.4k Golang : Generate thumbnails from images
+20.2k Golang : Convert(cast) string to rune and back to string example
+8.2k Golang : Generate Codabar