Methods of Reading & Writing Files

Reading and Writing Files
To read the files from the local filesystem, we need to use the 'io/ioutil' module. We need to pull some contents of a file into memory.
Example
Content of test.txt
Welcome to Coding Ninjas. This code demonstrates reading and writing operations to a file in Go lang.
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
)
func CreateFile() {
fmt.Printf("Writing to a file in Go lang\n")
file, err := os.Create("test.txt")
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
defer file.Close()
len, err := file.WriteString("Welcome to Coding Ninjas." +
"This code demonstrates reading and writing" +
"operations to a file in Go lang.")
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
fmt.Printf("\nFile Name: %s", file.Name())
fmt.Printf("\nLength: %d bytes", len)
}
func ReadFile() {
fmt.Printf("\n\nReading the file in Go lang.\n")
fileName := "test.txt"
data, err := ioutil.ReadFile("test.txt")
if err != nil {
log.Panicf("failed to read data from file: %s", err)
}
fmt.Printf("\nFile Name: %s", fileName)
fmt.Printf("\nSize: %d bytes", len(data))
fmt.Printf("\nData: %s", data)
}
func main() {
CreateFile()
ReadFile()
}
Output
Writing to a file in Go lang
File Name: test.txt
Length: 101 bytes
Reading a file in Go lang.
File Name: test.txt
Size: 101 bytes
Data: Welcome to Coding Ninjas. This code demonstrates reading and writing operations to a file in Go lang.
In this example, we have created a file; we input the data into that file. After inputting the data, we used several inbuilt functions to print the file name and size. We also print the data of the file.
Reading a file line by line
A file can also be read line by line—the function bufio.ReadString() is used to read the input line by line.
Example
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
)
func lineByLine(file string) error {
var err error
fd, err := os.Open(file)
if err != nil {
return err
}
defer fd.Close()
reader := bufio.NewReader(fd)
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
fmt.Printf("error reading file %s", err)
break
}
fmt.Print(line)
}
return nil
}
func main() {
flag.Parse()
if len(flag.Args()) == 0 {
fmt.Printf("usage: lByL <file1> [<file2> ...]\n")
return
}
for _, file := range flag.Args() {
err := lineByLine(file)
if err != nil {
fmt.Println(err)
}
}
}
Output
usage: lByL <file1> [<file2> ...]
In this example, we have read the file's content one by one. We checked certain conditions, and we showed a certain output.
FAQs
-
How do you read a file in go?
To read the files in Go, we use several packages: os, ioutil, io, and bufio.
-
What types of files can I read in Go?
In Go, we can read several types of files: CSV, PNG, or some proprietary data format.
-
How do I write content to a file in Go?
To write the content in the file, we need to use the io/util module.
Key Takeaways
In this article, we have extensively discussed the topic of Reading and Writing Files and their implementation in Golang.
We also explained a bit about Reading and Writing Files. We also discussed some of the inbuilt methods in the library. We took specific examples of reading and writing in files and their explanation.
We hope that this blog has helped you enhance your knowledge regarding Reading and Writing Files in GoLang and if you would like to learn more, check out our articles on Custom Errors in Go, Go Command Arguments.
Do upvote our blog to help other ninjas grow. Happy Coding!