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
+6.4k Golang : Combine slices of complex numbers and operation example
+7.2k Golang : How to detect if a sentence ends with a punctuation?
+15.9k Golang : How to reverse elements order in map ?
+17.9k Golang : How to log each HTTP request to your web server?
+5.3k Golang : Get S3 or CloudFront object or file information
+9.3k Golang : Scramble and unscramble text message by randomly replacing words
+18.7k Golang : Display list of time zones with GMT
+17.3k Golang : Linked list example
+11.4k Swift : Convert (cast) Float to String
+25.6k Golang : missing Mercurial command
+5.2k Golang : Pad file extension automagically
+11.2k Golang : Characters limiter example