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 : How to display image file or expose CSS, JS files from localhost?
+16.7k Golang : Check if a string contains multiple sub-strings in []string?
+88.9k Golang : How to convert character to ASCII and back
+32.3k Golang : Convert an image file to []byte
+10.7k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+11.8k Golang : Fuzzy string search or approximate string matching example
+11.9k Golang : How to detect a server/machine network interface capabilities?
+16.6k Golang : How to implement two-factor authentication?
+18.6k Golang : How to get hour, minute, second from time?
+19k Golang : Implement getters and setters
+12.7k Golang : Forwarding a local port to a remote server example
+7.5k Golang : Calculate how many weeks left to go in a given year