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
+4.8k JQuery : Calling a function inside Jquery(document) block
+21.9k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+17.4k Golang : Clone with pointer and modify value
+5k Golang : Check if a word is countable or not
+4.9k Golang : micron to centimeter example
+7.7k Golang : Getting Echo framework StartAutoTLS to work
+12.2k Golang : Display list of countries and ISO codes
+9.8k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+52.3k Golang : How to get struct field and value by name
+10.5k Golang : Bubble sort example
+22k Golang : Convert seconds to minutes and remainder seconds