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.7k Golang : Format strings to SEO friendly URL example
+7.5k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+13.3k Golang : Verify token from Google Authenticator App
+28.7k Golang : Detect (OS) Operating System
+8.6k Golang : How to join strings?
+8.9k Golang : Populate or initialize struct with values example
+21.8k Golang : Use TLS version 1.2 and enforce server security configuration over client
+5.2k Python : Convert(cast) string to bytes example
+25.6k Golang : How to write CSV data to file
+13.8k Golang : Get dimension(width and height) of image file
+8.1k Golang : Tell color name with OpenCV example
+4.2k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example