Introduction

Performing file input and output (I/O) is a fundamental part of many software applications. In this guide, we'll explore how to read and write files in Go, including the use of standard library functions and provide sample code to demonstrate their usage.


File Operations in Go

Go provides a straightforward way to perform file I/O. Common file operations include:

  • **Opening a File**: To open an existing file or create a new one.
  • **Reading from a File**: To read data from a file.
  • **Writing to a File**: To write data to a file.
  • **Closing a File**: To release resources associated with the file.

Opening a File

To open a file in Go, you can use the "os.Open" function. It returns a file descriptor, which you can use for reading or writing. Here's an example of opening a file for reading:

package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
}

In this code, we open a file named "example.txt" for reading and defer its closure to ensure it's closed after use.


Reading from a File

You can read data from a file using various methods. One common approach is to use a "bufio.Scanner" to read lines from a file. Here's an example:

package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, err := os.Open("example.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
}
}

In this code, we open a file, create a scanner, and read lines from the file. The data is printed to the console.


Writing to a File

To write data to a file in Go, you can use the "os.Create" function to create a new file or truncate an existing one. Here's an example of writing to a file:

package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Create("output.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
text := "Hello, Go!"
_, err = file.WriteString(text)
if err != nil {
fmt.Println("Error writing to file:", err)
}
}

In this code, we create a file named "output.txt," write the text "Hello, Go!" to it, and defer its closure.


Further Resources

To continue learning about basic file I/O in Go, consider these resources: