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.8k Golang : Error handling methods
+4.2k Golang : Pad file extension automagically
+21.6k Golang : Get ASCII code from a key press(cross-platform) example
+7.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+5.9k Golang : How to call function inside template with template.FuncMap
+4.4k PHP : Fix Call to undefined function curl_init() error
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+5.1k Golang : Get missing location after unmarshal binary and gob decode time.
+17.3k Golang : Padding data for encryption and un-padding data for decryption
+28k Golang : missing Git command
+9.8k Golang : Sieve of Eratosthenes algorithm