Skip to main content

Command Palette

Search for a command to run...

writing the file

Updated
1 min readView as Markdown
writing the file
S
DevRel at StackGen | Formerly at Deepfence ,Tenable , Accurics | AWS Community Builder also Docker Community Award Winner at Dockercon2020 | CyberSecurity Innovator of Year 2023 award by Bsides Bangalore | Docker/HashiCorp Meetup Organiser Bangalore & Co-Author of Learn Lightweight Kubernetes with k3s (2019) , Packt Publication & also run Non Profit CloudNativeFolks / CloudSecCorner Community To Empower Free Education reach out me twitterhttps://twitter.com/sangamtwts or just follow on GitHub -> https://github.com/sangam14 for Valuable Resources
  • Writing a file is an essential task for every programmer; Go supports multiple ways on how you can do this. This recipe will show a few of them.

Create the writefile.go file with the following content:

package main

import (
    "io"
    "os"
    "strings"
)

func main() {

    f, err := os.Create("sample.file")
    if err != nil {
        panic(err)
    }
    defer f.Close()

    _, err = f.WriteString("Go is awesome!\n")
    if err != nil {
        panic(err)
    }

    _, err = io.Copy(f, strings.NewReader("Yeah! Go is great.\n"))
    if err != nil {
        panic(err)
    }
}

output:

sangam:golang-daily sangam$  go run writefile.go

Check the content of the created sample.file:

sangam:golang-daily sangam$ cat sample.file 
Go is awesome!
Yeah! Go is great.
sangam:golang-daily sangam$

How it works...

  • The os.File type implements the Writer interface, so writing to the file could be done by any option that uses the Writer interface. The preceding example uses the WriteString method of the os.File type. The io.WriteString method can also be used in general.
2 views

GopherLabs

Part 1 of 50

Ultimate Series of Blogs for All Golang Developer

More from this blog

C

CloudNativeFolks Community

140 posts

CloudNativeFolks is non profit community that empower and educate about cloud native technology !