Golang Program to open a file in read-only mode


In Golang, read-only mode refers to a mode of operation in which a file, directory, or device can only be viewed or read, but not modified or deleted. This mode is used to prevent accidental changes in the data. In computer systems, the read-only mode can be set at the file or folder level, or it can be set for an entire disk or partition. In this article, we will use three Examples to open a file in read-only mode. In the first Example we will use open function from the os package, in the second Example we will use the ReadFile function from the ioutil package and in the third Example we will NewReader function from the bufio package respectively.

Syntax

file.read()

The Read() function is used to read the contents of a file. The function accepts the file whose contents are to be read as an argument and returns the contents of the file along with an error variable.

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

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.

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.

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 arguements in this function.

Example 1

In this Example we will use the open() function present in the os package in order to write a go language program to open a file in read only mode. We will use the Read() function in order to implement the result.

Algorithm

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

  • Then, start the main() function. Inside the main() define a variable called file and store in it the result obtained after calling the os.Open function and pass the name of the file as an argument to it.

  • Check if the error obtained by the function is nil or not. If it's not nil, print the error on the screen.

  • Call the "defer file.Close()" statement to close the file when the function executes successfully.

  • Read from the file using the "file.Read" method.

  • Print the contents of the file on the screen by converting them to strings.

package main

import (
   "fmt"
   "os"
)

func main() {
   // Open the file in read-only mode
   file, err := os.Open("newfile.txt")
   if err != nil {
      panic(err)
   }
   defer file.Close()

   // Read the contents of the file
   b := make([]byte, 1024)
   _, err = file.Read(b)
   if err != nil {
      panic(err)
   }

   // Print the contents of the file
   fmt.Println("The given file is opened in read-only mode and its contents are:\n", string(b))
}

Output

The given file is opened in read-only mode and its contents are:
Hello, World!

Example 2

In this Example we will write a go language program to open a file in read-only mode by using the readFile() function present in the ioutil package. This function reads the entire contents of a file and returns it as a slice of bytes.

Algorithm

  • First, we need to import the “ioutil”and “fmt” packages.

  • Then, start the main() function. Inside the main() define a variable "data" of type []byte and a variable "err" of type error.

  • Call the ioutil.ReadFile function, passing the name of the file as an argument to it.

  • Store the result of the function in the variable called data.

  • If the error variable returned by the function is not nil then print the error on the screen by using fmt.Println() function.

  • The file is automatically closed when the function executes successfully.

package main

import (
   "fmt"
   "io/ioutil"
)

func main() {
   // Read the entire contents of the file
   data, err := ioutil.ReadFile("newfile.txt")
   if err != nil {
      panic(err)
   }

   // Print the contents of the file
   fmt.Println("The given file is opened in read-only mode and its contents are:\n", string(data))
}

Output

The given file is opened in read-only mode and its contents are:
Hello, World!

Example 3

In this Example we will write a go language program to open a file in read only mode by using the newreader() function present in bufio package. This function creates a new reader that implements the reader interface.

Algorithm

  • First we need to import the "bufio" and "os" packages.

  • Then start the main() function. Inside the main()call the Open() function present in the os package and passthe name of the file as an argument to it.

  • Store the result of the function in the file variable.

  • Check if the error variable is not nil. If it's not nil print the error on the screen by using fmt.Println() function.

  • Create a new reader using the bufio.NewReader() function and pass the name of the file as argument to that function.

  • If the error variable received by the function is not nil then print the error on the screen. otherwise print that the given file is opened in read-write mode.

package main

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

func main() {
   // Open the file in read-only mode
   file, err := os.Open("newfile.txt")
   if err != nil {
      panic(err)
   }
   defer file.Close()

   // Create a new reader
   reader := bufio.NewReader(file)

   // Read the contents of the file
   b, _, err := reader.ReadLine()
   if err != nil {
      panic(err)
   }

   // Print the contents of the file
   fmt.Println("The given file is opened in read-only mode and its contents are:\n", string(b))
}

Output

The given file is opened in read-only mode and its contents are:
Hello, World!

Conclusion

We have successfully compiled and executed a go language program to open a file in read-only mode along with Examples. In the first Example we have used File.Read() function while in the second and third Example we have used ReadFile() and NewReader() function respectively.

Updated on: 03-May-2023

994 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements