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
+32.1k Golang : Proper way to set function argument default value
+32.3k Golang : Get file last modified date and time
+13.1k Golang : How to get Unix file descriptor for console and file
+13.9k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+18.8k Golang : Encrypt and decrypt data with TripleDES
+5.4k Linux : How to fix Brother HL-1110 printing blank page problem
+3.7k Golang : Calculate half life decay example
+7.4k Golang : Take screen shot of browser with JQuery example
+16.8k Golang : Get current URL example
+6.5k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+8.6k Golang : Wait and sync.WaitGroup example