In this tutorial, we will dive into how to handle files in Go programming language. Specifically, we will be using the os
package in Go to open, read, write, and close files.
By the end of this tutorial, you will learn:
- How to open a file in Go
- How to read from a file
- How to write to a file
- How to close a file once done
Prerequisites: Basic understanding of Go programming language.
Go has built-in support for reading and writing files using the os
package. Here are the key concepts:
Opening a File: The os.Open()
function is used to open a file.
file, err := os.Open("test.txt")
Reading a File: The io/ioutil
package provides helper functions for reading a file.
data, err := ioutil.ReadFile("test.txt")
Writing to a File: The os.Create()
function is used to create a file, and file.WriteString()
is used to write to a file.
file, err := os.Create("test.txt")
n, err := file.WriteString("Hello World")
Closing a File: The file.Close()
function is used to close the file.
err = file.Close()
Let's look at some practical examples:
Example 1: Reading a file
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
// Open file for reading
data, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Fatalf("Failed reading data from file: %s", err)
}
fmt.Printf("Data read: %s\n", data)
}
In this example, we open a file called "test.txt" and read all data from it.
Example 2: Writing a file
package main
import (
"log"
"os"
)
func main() {
// Create a new file
file, err := os.Create("test.txt")
if err != nil {
log.Fatalf("Failed creating file: %s", err)
}
// Write some text line-by-line to file.
_, err = file.WriteString("Hello\nWorld")
if err != nil {
log.Fatalf("Failed writing to file: %s", err)
}
// Close the file
file.Close()
}
In this example, we create a new file and write two lines of text to it. Don't forget to close the file after writing to it.
In this tutorial, we learned how to open, read, write, and close files in Go using the os
and io/ioutil
packages.
For further learning, explore how to handle errors in Go and how to read and write to CSV and JSON files.
Check out the official Go documentation for more details.
Solutions
1.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineCount := 0
for scanner.Scan() {
lineCount++
}
fmt.Println("Number of lines:", lineCount)
}
This program opens the file, scans each line, and increments a counter for each line.
2.
package main
import (
"fmt"
"log"
"os"
)
func main() {
file, err := os.Create("numbers.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
for i := 1; i <= 10; i++ {
fmt.Fprintln(file, i)
}
}
This program creates a file and writes the numbers 1 to 10, each on a new line.
3.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
lineNumber := 0
for scanner.Scan() {
lineNumber++
if lineNumber%2 == 0 {
fmt.Println(scanner.Text())
}
}
}
This program reads a file and prints only the even numbered lines.