Go File Reading: Methods & Code Examples
In Go language, there are several methods for reading files.
- Use the ReadFile method from the ioutil package to read the entire content of a file. Here is an example code snippet:
package main
import (
"io/ioutil"
"fmt"
)
func main() {
data, err := ioutil.ReadFile("file.txt")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println(string(data))
}
- Use the Open method and Read method from the os package to read the contents of a file line by line. Sample code is shown below:
package main
import (
"os"
"bufio"
"fmt"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
}
}
- The content of a file can be read byte by byte using the Open and Read methods of the os package. Here is an example code snippet:
package main
import (
"os"
"fmt"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
data := make([]byte, 1024)
for {
n, err := file.Read(data)
if n == 0 || err != nil {
break
}
fmt.Print(string(data[:n]))
}
}
The above are several methods for reading files in the Go language, developers can choose the appropriate method according to their own needs.