Golang Program to Read the Contents of a File

pre.prettyprint{width:99%!important;} a.demo{top:12px!important; float:right!important;}

To read the contents of a file, we can take following steps −

  • We can create a file called test.txt.
  • Clean-up using defer statement.
  • Write the contents of string.
  • Call ReadFile() method to read the file.
  • ReadFile reads the file named by filename and returns the contents.
  • Print the content of the file.


 Live Demo

package main
import (
func CreateFile() {
   file, err := os.Create("test.txt")
   if err != nil {
      log.Fatalf("failed creating file: %s", err)
   defer file.Close()
   _, err = file.WriteString("Welcome to Tutorials Point")
   if err != nil {
      log.Fatalf("failed writing to file: %s", err)
func ReadFile() {
   fileName := "test.txt"
   data, err := ioutil.ReadFile(fileName)
   if err != nil {
      log.Panicf("failed reading data from file: %s", err)
   fmt.Printf("\n%s", data)
func main() {


Welcome to Tutorials Point

Updated on: 30-Jul-2021


Kickstart Your Career

Get certified by completing the course

Get Started