In Go, you can read and write files using the ‘os‘ and ‘io/ioutil‘ packages. Here, I’ll explain how to read and write files in Go with step-by-step examples.
**Reading a file in Go**
1. Import the required packages
package main
import (
"fmt"
"io/ioutil"
"log"
)
2. Use the ‘ioutil.ReadFile()‘ function to read the file.
func main() {
content, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("File content:")
fmt.Println(string(content))
}
Here, ‘ioutil.ReadFile()‘ reads the file ‘test.txt‘ and returns its content as a byte slice. If there’s an error reading the file, it will be handled by the ‘log.Fatal()‘ function.
**Writing a file in Go**
1. Import the required packages
package main
import (
"fmt"
"io/ioutil"
"log"
)
2. Use the ‘ioutil.WriteFile()‘ function to write to a file.
func main() {
data := []byte("Hello, World!n")
err := ioutil.WriteFile("output.txt", data, 0644)
if err != nil {
log.Fatal(err)
}
fmt.Println("Data written to file successfully.")
}
Here, we create a byte slice named ‘data‘ with the content we want to write to the file. Then, ‘ioutil.WriteFile()‘ is used to write the content to a file named ‘output.txt‘ with the permission mode ‘0644‘. If there’s an error writing the file, it will be handled by the ‘log.Fatal()‘ function.
These examples above use the ‘io/ioutil‘ package, which is now deprecated as of Go 1.16. If you’re using Go 1.16 or later, you can use the following examples:
**Reading a file in Go 1.16**
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
content, err := os.ReadFile("test.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println("File content:")
fmt.Println(string(content))
}
**Writing a file in Go 1.16**
package main
import (
"fmt"
"os"
"log"
)
func main() {
data := []byte("Hello, World!n")
err := os.WriteFile("output.txt", data, 0644)
if err != nil {
log.Fatal(err)
}
fmt.Println("Data written to file successfully.")
}
In these examples, we replaced ‘ioutil.ReadFile()‘ and ‘ioutil.WriteFile()‘ with ‘os.ReadFile()‘ and ‘os.WriteFile()‘ respectively. The rest of the code remains the same.