WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Basic · question 14 of 100

How do you read and write files in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics