Menu Close

Go – How to write into a file in go

In this article, We are going to see how to write into a file in go with example in details.

We can do it by using either WriteString() or WriteAt() or Write() or WriteFile() function in os package in go golang.

WriteString() function

Function prototype:

func (f *File) WriteString(str string) (n int, err error)

Input Parameter:

str : file name

WriteString() function writes the string into file.

Return value:

WriteString() function in os package returns 
the number of bytes written and an error, if any.

Example with code:

package main

import (
  "fmt"
  "os"
  "log"
)

func main() {

  file_name := "/Users/hello.go"

  file, err := os.Create(file_name)

  if err != nil {

    log.Fatal(err)

    os.Exit(-1)

  }

  var bytes int

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


  if err != nil {

    log.Fatal(err)

    os.Exit(-1)

  }

  fmt.Println("Bytes Written in file: ", bytes)

  defer file.Close()
}

Output:

$ sudo go run sample.go
Bytes Written in file: 8

$ ls -lrt hello.go
-rw-r--r-- 1 root staff 8 May 5 20:22 hello.go

$cat hello.go
Hello Go

Write() function

Function prototype:

func (f *File) Write(b []byte) (n int, err error)

b: String to be written in byte array

Write() writes len(b) bytes to the File.

Return value:

Write() function in os package returns
the number of bytes written and an error, if any.

Example with code:

package main

import (
  "fmt"
  "os"
  "log"
)

func main() {

  file_name := "/Users/hello.go"

  file, err := os.Create(file_name)

  if err != nil {

    log.Fatal(err)

    os.Exit(-1)

  }


  str := []byte("Hello Go")

  var bytes int

  bytes, err = file.Write(str)


  if err != nil {

    log.Fatal(err)

    os.Exit(-1)

  }

  fmt.Println("Bytes Written in file: ", bytes)

  defer file.Close()
}

Output:

$ sudo go run sample.go
Bytes Written in file: 8

$ ls -lrt hello.go
-rw-r--r-- 1 root staff 8 May 5 20:22 hello.go

$cat hello.go
Hello Go

WriteFile() Function

Function prototype:

func WriteFile(filename string, data []byte, perm os.FileMode) error

Return value:

WriteFile() function in ioutil package returns
an error, if any.

Example with code:

package main

import (
  "io/ioutil"
  "log"
)

func main() {

  file_name := "/Users/hello.go"

  data := []byte("Hello go")

  err := ioutil.WriteFile(file_name, data, 0644)

  if err != nil {

    log.Fatal(err)

  }
}

Output:

$ sudo go run sample.go

$ ls -lrt hello.go
-rw-r--r-- 1 root staff 5 May 6 19:05 hello.goo

$cat hello.go
Hello

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, os, packages

Leave a Reply

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