Menu Close

Go – How to read a file in go

Here, We will see how to read a file in go. We can do it by using ReadFile() function in ioutil package in go golang.

Function prototype:

func ReadFile(filename string) ([]byte, error)

Return value:

Reafile() function in ioutil package reads 
the file named by filename and returns the contents.

Example with code:

import (
  "fmt"
  "os"
  "log"
  "io/ioutil"
)

func main() {

  file_name := "/Users/hello.go"

  file, err := os.Create(file_name)

  if err != nil {

    log.Fatal(err)

    os.Exit(-1)

  }

  _, err = file.WriteString("Hello Go")


  if err != nil {

    log.Fatal(err)

    os.Exit(-1)

  }

  content, err := ioutil.ReadFile(file_name)

  if err != nil {

    log.Fatal(err)

  }

  fmt.Printf("File contents: %s", content)

  defer file.Close()
}

Output:

sudo go run sample.go

File contents: Hello Go

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, ioutil, packages

Leave a Reply

Your email address will not be published. Required fields are marked *