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
+8.9k Yum Error: no such table: packages
+17.8k Golang : Read data from config file and assign to variables
+7.7k Android Studio : AlertDialog to get user attention example
+5.1k Golang : micron to centimeter example
+12.1k Golang : Determine if time variables have same calendar day
+12.9k Golang : Convert int(year) to time.Time type
+6.2k Golang : Measure execution time for a function
+5.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+12.3k Golang : Split strings into command line arguments
+14.2k Golang : Compress and decompress file with compress/flate example
+17.8k Golang : [json: cannot unmarshal object into Go value of type]
+25.4k Golang : Get current file path of a file or executable