Golang Program to read the specified number of characters from the existing file


In golang we can use ioutile.ReadFile() to read the file and for loop timer, we will limit the character numbers to read, Os.Open and bufio.NewReader function to perform the execution as well as file.Read() respectively. In this article we will learn how to use the OS asnd bufio package of Golang to read the specified number of characters from the existing file.

Syntax

ioutil.ReadFile(file)

The ReadFile() function is present in ioutil package and is used to read the given file. The function accepts the file to be read as argument to the function. To read a specified number of characters from the file, we can use the ReadFile function and then extract the desired number of characters from the returned byte slice.

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.

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.

Method 1

In this method, we will use the Read() function present in ioutil package to read the characters from an existing file.

Algorithm

  • First, we need to import the fmt and ioutil package.

  • Now, start the main() function. Inside the main() use the ReadFile() function to read the contents of the file.

  • Check for any errors while reading the file.If an error occurs, print the error message on the screen.

  • If no error is generated, then print the contents of the file on the screen.

  • Print the sliced byte slice as a string using the fmt.Println function.

Example

In the following Example,we will create a golang program to read the specified number of characters from the existing file using ioutil package.

package main

import (
   "fmt"
   "io/ioutil"
)

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

   if len(content) < 5 {
      fmt.Println("File is too small to read 5 characters")
      return
   }

   characters := content[:]
   fmt.Println("The contents of given file are:\n", string(characters))
}

Output

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.

Method 2

In this method, we will write a go language program to read the specified characters from the file by using the Read() function present in the bufio package. To read a specified number of characters from a file using the bufio package, we can use the NewReader function to create a new buffered reader and then use the Read method to read the desired number of characters.

Algorithm

  • First, we need to import the “os”, "fmt" and "bufio" packages.

  • Now, call the main() function. Inside the main() call Open() function in order to open the file and call the bufio.NewReader function to create a new reader for the file.

  • Use the reader's Read method to read a specified number of characters into a byte slice.

  • Check if an error occurs while reading the file.If an error occurs, print an error message on the screen.

  • If no error occurs, print the byte slice as a string using the fmt.Println function.

Example

In this Example, we will learn how to use OS and Bufio packages of golang to read the specified number of characters from the existing file.

package main

import (
   "bufio"
   "fmt"
   "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)
   characters := make([]byte, 400)
   n, err := reader.Read(characters)
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }

   if n < 5 {
      fmt.Println("File is too small to read 5 characters")
      return
   }
   fmt.Println(string(characters))
}

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.

Method 3

In this method, we will write a go language program to read the specified number of characters from the existing files by using various functions present in io package.

Algorithm

  • First, we need to import the "fmt", "io", and "os" packages.

  • Then, start the main() function. Inside the main() use the os.Open function to open the file.

  • Check if an error occurs while opening the file.If an error occurs, print an error message and return.

  • If no error occurs, use the file's Read method to read a specified number of characters into a byte slice.

  • Check if an error occurs while reading the file.

  • If an error occurs, print an error message and return.If no error occurs, check if the number of characters actually read is less than the desired number of characters.

  • If it is, print a message saying that the file is too small to read the desired number of characters.

  • If the number of characters actually read is equal to or greater than the desired number of characters, print the byte slice as a string using the fmt.Println function.

Example

In this Example, we are going to learn how to create golang program to read the specified number of characters from the existing file using io and os packages.

package main

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

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

   characters := make([]byte, 450)
   n, err := file.Read(characters)
   if err != nil && err != io.EOF {
      fmt.Println("Error reading file:", err)
      return
   }

   if n < 5 {
      fmt.Println("File is too small to read 5 characters")
      return
   }

   fmt.Println(string(characters))
}

Output

Modern humans (Homo sapiens), the species? that we are, means ‘wise man’ in Latin. Our species is the only surviving species of the genus
Homo but where we came from has been a topic of much debate. Modern humans originated in Africa within the past 200,000 years
and evolved from their most likely recent common ancestor, Homo erectus, which means ‘upright man’ in Latin.
Homo erectus is an extinct species of human that lived between 1.9 million and 135,000 years ago.

Conclusion

We have successfully compiled and executed a go language program to read the specified number of characters from the existing file along with Examples.Here we have used three Examples. In the first Example we have used the ioutil package provides an easy-to-use function for reading files, while the bufio and io packages provide more flexible and efficient methods for reading files which are used in second Example and in the third Example we have used the os package.

Updated on: 03-May-2023

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements