You are currently viewing Introduction to File I/O in Go

Introduction to File I/O in Go

  • Post author:
  • Post category:Go
  • Post comments:0 Comments
  • Post last modified:May 12, 2024

File Input/Output (I/O) operations are essential for interacting with files in any programming language. Go (Golang) provides a rich set of standard library functions for performing file I/O operations efficiently. This tutorial will guide you through the basics of handling file I/O in Go with code examples.

1. Opening and Closing Files

Opening a File

To open a file in Go, you can use the os.Open() function. It returns a file pointer and an error if any.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("example.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer file.Close()
    // File operations here
}

Closing a File

It’s essential to close the file after performing operations to release system resources. You can use the file.Close() method or defer it immediately after opening the file.

2. Reading from Files

Reading Entire File Contents

You can read the entire contents of a file using io/ioutil package.

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    content, err := ioutil.ReadFile("example.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println(string(content))
}

Reading File Line by Line

To read a file line by line, you can use the bufio package.

package main

import (
    "bufio"
    "fmt"
    "os"
)

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

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
}

3. Writing to Files

Writing to Files

To write data to a file, you can use the os.Create() function.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Create("output.txt")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer file.Close()

    _, err = file.WriteString("Hello, World!")
    if err != nil {
        fmt.Println("Error:", err)
    }
}

Conclusion

File I/O operations are fundamental for many Go applications. With the standard library functions provided by Go, handling file operations becomes straightforward. Practice these examples to master file I/O in Go and enhance your programming skills.

Leave a Reply