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
+17.7k Golang : [json: cannot unmarshal object into Go value of type]
+13.7k Golang : Set image canvas or background to transparent
+5.2k Golang : Issue HTTP commands to server and port example
+16.6k Golang : Get IP addresses of a domain name
+5k Python : Convert(cast) bytes to string example
+14.9k Golang : Get URI segments by number and assign as variable example
+18k Golang : Simple client server example
+11.6k Swift : Convert (cast) Float to String
+7.3k Golang : Dealing with postal or zip code example
+5.8k Golang : Find change in a combination of coins example
+5.7k Golang : Frobnicate or tweaking a string example
+31.6k Golang : bufio.NewReader.ReadLine to read file line by line