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
+10.7k Golang : Send email with attachment
+13.6k Golang : Delete duplicate items from a slice/array
+6.1k Golang : Setting variable value with ldflags
+3.6k Golang : Scanf function weird error in Windows
+14.4k PHP : Convert(cast) string to bigInt
+2.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+2.3k Golang : Calculate half life decay example
+3.6k Golang : Rename part of filename
+3.5k Golang : Embedded or data bundling example
+4.2k Golang : Inject/embed Javascript before sending out to browser example
+3.3k Apt-get to install and uninstall Golang
+5.8k Golang : Channels and buffered channels examples