Go Lang - File I/O
Reading from and Writing to Files in Go
File I/O in Go involves reading data from files and writing data to files.
Key Points:
- Go provides built-in packages like 'os' and 'bufio' for file handling.
- Reading from a file involves opening a file, reading its contents, and closing the file.
- Writing to a file involves creating or opening a file, writing data to it, and closing the file.
Example of File I/O in Go
Below is an example demonstrating reading from and writing to files in Go:
// Example: File I/O in Go
package main
import (
"fmt"
"os"
"bufio"
)
func main() {
// Writing to a file
fileWrite, err := os.Create("output.txt")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer fileWrite.Close()
// Write data to the file
data := "Hello, World!\n"
_, err = fileWrite.WriteString(data)
if err != nil {
fmt.Println("Error writing to file:", err)
return
}
fmt.Println("Data written to file successfully.")
// Reading from a file
fileRead, err := os.Open("input.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer fileRead.Close()
scanner := bufio.NewScanner(fileRead)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("Error scanning file:", err)
return
}
}
Summary
This guide provided an overview of reading from and writing to files in Go, including examples of creating, opening, writing to, and reading from files using built-in packages like 'os' and 'bufio'. By using file I/O operations effectively, you can handle file data in Go applications seamlessly.