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.4k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+31.3k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+36.2k Golang : Convert(cast) int64 to string
+8k Golang : HTTP Server Example
+12.1k Golang : List running EC2 instances and descriptions
+15.4k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+10.3k Golang : Meaning of omitempty in struct's field tag
+7.9k Findstr command the Grep equivalent for Windows
+6.1k Linux/Unix : Commands that you need to be careful about
+7k Golang : Transform lisp or spinal case to Pascal case example
+31.2k Golang : bufio.NewReader.ReadLine to read file line by line
+6.4k Golang : Convert an executable file into []byte example