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
+7.9k Javascript : How to check a browser's Do Not Track status?
+4.6k JavaScript : Rounding number to decimal formats to display currency
+23.8k Find and replace a character in a string in Go
+12.5k Golang : Extract part of string with regular expression
+6.6k Golang : Map within a map example
+8.1k Golang : Append and add item in slice
+8.4k Golang : Count leading or ending zeros(any item of interest) example
+12.8k Swift : Convert (cast) Int or int32 value to CGFloat
+29.5k Golang : Login(Authenticate) with Facebook example
+16.5k Golang : Test floating point numbers not-a-number and infinite example
+30.5k Get client IP Address in Go