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
+4.9k Golang : Display packages names during compilation
+9.6k Golang : Find correlation coefficient example
+16.8k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error
+8.5k Golang : Progress bar with ∎ character
+13.9k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+7.6k Gogland : Where to put source code files in package directory for rookie
+9.4k Golang : How to extract video or image files from html source code
+9.3k Golang : Accessing content anonymously with Tor
+6.1k Golang & Javascript : How to save cropped image to file on server
+5.5k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+12.7k Golang : Convert int(year) to time.Time type
+7.9k Golang : What fmt.Println() can do and println() cannot do