Golang : Read file and convert content to string
Problem :
You want to read a file content and convert the content into string.
Solution :
Read the file with ioutil.ReadFile() function. The file content will be in []byte and you just convert the byte into string
s := string(filecontent)
Below is a full example :
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))
}
References :
http://golang.org/pkg/io/ioutil/#ReadFile
https://www.socketloop.com/tutorials/golang-read-file-with-ioutil
See also : Golang : Read a file line by line
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
+9.5k Golang : How to transmit update file to client by HTTP request example
+24.5k Golang : How to write CSV data to file
+11.9k Golang : Increment string example
+3.9k Golang : Calculate a pip value and distance to target profit example
+4.8k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+7.8k Golang : Capture text return from exec function example
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+5k Facebook : How to force facebook to scrape latest URL link data?
+18.5k Golang : Append content to a file
+11.7k Generate salted password with OpenSSL example
+7.9k Golang : Apply Histogram Equalization to color images
+10.4k Golang : flag provided but not defined error