Golang Program to read lines from the existing file


In Go programming language, Bufio and io package functions will be used to read the text from the given file. In this article, we will use three Examples to read lines from the existing file. In the first Example, we will use NewReader function from the bufio package, in the second Example we will use ReadFile function from ioutil package and in the third Example we will use file.Read function respectively.

Syntax

func Split(str, sep string) []string

Split() function is used to split a string through a provided separator. This function is present in strings package and it accepts the string to split as an argument along with a separator. The function then returns the final array of strings as a result.

bufio.NewReader()

This function belongs to Go's bufio package. The primary goal of this function is to read the data in larger chunks instead of line by line and store in buffer. The io.reader and buffer size are passed as arguments in this function.

os.Open()

This function is a part of os package. It is used to open a file to read. It takes one input i.e. the filename which will be opened.

ioutil.ReadFile()

This function is available in the ioutil package and is used to read the contents of a file with filename as an input in the function.

File.Read(file name)

The Read method returns two values: the number of characters actually read (n) and an error (err). We check if there was an error and, if there was, we check if the error is an EOF (end-of-file) error. If it's not an EOF error, we print an error message and return.

Algorithm

  • Import the desired packages in the program

  • Create a main function

  • In main open the file and read its contents

  • If error is encountered print it on the console

Example 1

In this Example we will write a go language program to read lines from the existing file by using NewReader() function present in bufio package. The ReadString method of the reader is then used to read lines from the file.

package main

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

func main() {
   file, err := os.Open("file.txt")
   if err != nil {
      fmt.Println("Error opening file:", err)
      return
   }
   defer file.Close()
   reader := bufio.NewReader(file)
   fmt.Println("Data recieved after reading from the file is:\n")	
   for {
      line, err := reader.ReadString('\n')
		if err == io.EOF {
         break
      }
      if err != nil {
         fmt.Println("Error reading line:", err)
         return
      }
      fmt.Println(line)
   }
}

Output

Data received after reading from the file is:

History of Computers

It is very difficult to find the exact origin of computers.

But according to some experts computer exists at the time of world war-II.

Also, at that time they were used for keeping data. But, it was for only government use and not for public use.

Example 2

In this Example we will write a go language program to read lines from the existing files by using the Split function present in strings package and ReadFile() function present in ioutil package.

package main

import (
   "fmt"
   "io/ioutil"
   "strings"
)

func main() {
   contents, err := ioutil.ReadFile("file.txt")
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }

   lines := strings.Split(string(contents), "\n")
   fmt.Println("Data received after reading lines from the file specified is:\n")
   for _, line := range lines {
      fmt.Println(line)
   }
}

Output

Data received after reading lines from the file specified is:

History of Computers
It is very difficult to find the exact origin of computers.
But according to some experts computer exists at the time of world war-II.
Also, at that time they were used for keeping data. But, it was for only government use and not for public use.
Above all, in the beginning, the computer was a very large and heavy machine.

Example 3

The third method for reading lines from a file in Golang is to use a loop to read the file line by line. The os.Open function is used to open the file, and the file.Read method is used to read the contents of the file into a byte slice. The bytes.IndexByte function is then used to find the newline character in the byte slice, and the slice is converted to a string using the string function.

package main

import (
   "bytes"
   "fmt"
   "io"
   "os"
)

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

   var buffer bytes.Buffer
   for {
      b := make([]byte, 1024)
      n, err := file.Read(b)
      if err == io.EOF {
         break
      }
      if err != nil {
         fmt.Println("Error reading file:", err)
         return
      }
      buffer.Write(b[:n])
      for {
         index := bytes.IndexByte(buffer.Bytes(), '\n')
         if index == -1 {
            break
         }
         line := buffer.Next(index + 1)
         fmt.Println(string(line))
      }
   }
}

Output

The history of programming languages spans from documentation of early mechanical computers to modern

tools for software development. Early programming languages were highly specialized, relying on

mathematical notation and similarly obscure Syntax. Throughout the 20th century, research in compiler

theory led to the creation of high-level programming languages.

Conclusion

We have successfully complied and executed a go language program to read lines from the existing files along with the Examples.We have used three Examples here in order to implement the result. Depending on the use case, one of these Examples may be more suitable than the others. Regardless of the method used, it is important to handle errors correctly when reading files in Golang.

Updated on: 03-May-2023

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements