Read and Write files in Golang
Tags: go, file, tutorial, webdev
Published: 2024-04-27 17:01:48

In this tutorial, we will learn how to read, write, and append to a file using Golang.

The built-in `os` package provides reading and writing files. Earlier it used to be handled by `io/ioutil` package. 

A file must have correct file permissions to perform respective operations.

Following are the file modes(permissions) codes that we will need in the tutorial.

```
0000     no permissions
0700     read, write, & execute only for the owner
0770     read, write, & execute for owner and group
0777     read, write, & execute for owner, group and others
0111     execute
0222     write
0333     write & execute
0444     read
0555     read & execute
0666     read & write
0740     owner can read, write, & execute; group can only read; others have no permissions
```

You can also watch this tutorial on YouTube.
{% embed https://youtu.be/lkeh0TRSBfo?si=Om4wal2ngJ4x9hzs %}

## Write file in golang
The `os.Writefile` function accepts the filename or full path with extension if any, data or content in `[]byte` format and file permission code.

### Syntax
```
func WriteFile(name string, data []byte, perm os.FileMode) error
```

The below code will create a new file if it doesn't exist and write or it will override with new content to the existing file. 
The `0777` file mode gives read, write and execution permission.
The `data` is a string converted to `[]byte` format.

```go
package main

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

func main() {
	data := []byte("dev.to")
	err := os.WriteFile("test.txt", data, 0777)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("file written successfully.")
}
```

## Read file in golang

The `os.ReadFile` function accepts the filename or full file path and returns `[]byte` and error.

It will throw an error if the file doesn't exist or the file doesn't have permission to read.

### Syntax
```
func ReadFile(name string) ([]byte, error)
```

```
package main

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

func main() {
	data, err := os.ReadFile("test.txt")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(data))
}
```

## Append to an existing file

There are 2 ways you can append content to an existing file.

### 1. Read and Write

In this approach, first read the file, append the content and then write the file.

```
package main

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

func main() {
	data, err := os.ReadFile("test.txt")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(data))

	msg := []byte("\nappended message")

	data = append(data, msg...)

	err = os.WriteFile("test.txt", data, 0777)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("file written successfully.")
}
```

### 2. Open and write

In this approach, first, open the file with the `O_APPEND` flag then write the content and close the file.

```
package main

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

func main() {
	file, err := os.OpenFile("test.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777)
	if err != nil {
		log.Fatal(err)
	}

	defer file.Close()

	msg := []byte("\n another appended message")
	_, err = file.Write(msg)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("file appended successfully.")
}
```

`os.O_APPEND` - File permission append
`os.O_CREATE` - Create a new file if it doesn't exist
`os.O_WRONLY` - Write only

---
I hope you like this tutorial. 
Happy Coding. Please Follow and Subscribe to YouTube.

{% embed https://youtu.be/wJ6JP22YOUk %}