Golang Program to Read the Contents of a File

Go ProgrammingServer Side ProgrammingProgramming

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.

Example

 Live Demo

package main
import (
   "fmt"
   "io/ioutil"
   "log"
   "os"
)
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() {
   CreateFile()
   ReadFile()
}

Output

Welcome to Tutorials Point
raja
Published on 30-Jul-2021 07:12:01
Advertisements