golang

Golang Write to File

This guide will help you explore the technique of writing to a file using the Go programming language.

The Basics

In most cases, we will handle file operations in Go using the os and ioutil package. These packages come packed with tools and utilities for working with files and directories.

Let us start with the basics and discuss how to write data to files.

Golang Create File

The first step to writing any data to a file is to ensure the file exists. For this, we can create a file using the os.Create() method.

You can check out other techniques for creating a file in our tutorial on the topic.

The function takes the name of the file to create as the argument. An example code is as shown:

package main
import (
    "log"
    "os"
)
funcmain() {
    // create a file and check for errors
    file, err := os.Create("info.txt")
    if err != nil {
        log.Fatal(err)
    }
    // close the file
    deferfile.Close()
}

In the previous example, we use the os.Create() method to create a file called info.txt in the current working directory.

We also closed the file using the deferred file.Close() method.

Write Strings to a File

The first method we can use to write to a file is the ioutil.WriteFile() method. This function writes a sequence of characters to a file with minimal effort. It is very similar to the Write() function except it converts the sequence of bytes into a string before writing to the file.

Note: we need to specify the file permission before writing to the file.

An example is as shown:

package main
import (
    "io/ioutil"
    "log"
)
funcmain() {
    b := []byte("Hello world string")
    err := ioutil.WriteFile("info.txt", b, 0644)
    if err != nil {
        log.Fatal(err)
    }
}

The function takes a byte slice and writes it into the specified file as a string. If we can create the info.txt file, we can see the content as:

$ cat info.txt

Hello world string

Write Byte to a File

As mentioned, the WriteFile method writes a string to a file. If you wish to write a sequence of bytes to a file, you can use the Write method. An example source code is as shown below:

package main
import (
    "log"
    "os"
)
funcmain() {
    file, err := os.Create("info.txt")
    if err != nil {
        log.Fatal(err)
    }
    deferfile.Close()
    bytes := []byte("A second sequence of bytes")
    file.Write(bytes)
}

In the previous example, we create a file using the os package and write a sequence of bytes using the Write method.

Append an Existing File

You can also append data into an existing file. In such an example, we open the file using the OpenFile method.

An example is provided below:

package main
import (
    "fmt"
    "log"
    "os"
)
func main() {
    file, err := os.OpenFile("info.txt", os.O_APPEND|os.O_WRONLY, 0644)
    iferr != nil {
        log.Fatal(err)
        return
    }
    nl := "\nText appended to the second line"
    _, err = fmt.Fprintln(file, nl)
    iferr != nil {
        log.Fatal()
    }
}

The previous code opens a file for reading and writing, as specified in the O_APPEND and O_WRONLY flags.

Then, we use the fmt.Fprintln method to append the string to a file. If we can create the info.txt file, we can view the content as:

$ cat info.txt

Hello world string

Text appended to the second line

Conclusion

This piece covers file writing and appending operations in the Go programming language. The process includes learning the basics, creating a file, writing strings, writing bytes, and appending an existing file. We hope you found this article helpful. Check out other Linux Hint articles for more tips and information.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list