Hello everyone, welcome to the Golang tutorial series. In this post, you will learn how to read a file in golang and this example program has been tested and shared in the same post.

The operations such as reading and writing a file in golang is a pretty easiest task to do it. In this post, we will see a quick example to read a file in go using ReadFile() function from ioutil package. The ReadFile() function will take a file name as an argument(string type) and it will return two values such as data([]byte) and error.
Example – Reading a File in Golang
In the below example, we are trying to read file content from a given file name also, we have handled an error during the unexpected scenarios. Once, the ReadFile() function ran successfully you will get []byte of a file data and same can be passed to string() function to print output.
File Content

package main import ( "fmt" "io/ioutil" ) func main() { data, error := ioutil.ReadFile("data.txt") if error != nil { fmt.Println(error) return } fmt.Println(string(data)) }
References
- https://golang.org/doc/
- https://golang.org/pkg/
- https://golang.org/pkg/fmt/
- https://golang.org/pkg/fmt/#Println
- https://golang.org/pkg/io/ioutil/#ReadFile
More from my site

Hello, folks, I am a founder of idineshkrishnan.com. I love open source technologies, If you find my tutorials are useful, please consider making donations to these charities.
No responses yet