Golang program to create string from contents of a file


In go we can use io and os package to perform various operations with file. In this article, we are going to use ioutil.readfile function to read the file and then the string function to convert the file data to string. From OS package we are going to use os.open to open the file and use string operation to convert the data to string.

Method 1: Using io/ioutil package

In this illustration, the file's contents are read into a byte slice using the ioutil.ReadFile function. The byte slice is subsequently transformed into a string using the string function. The contents of the file are then printed to the console using fmt package.

Syntax

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.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), io/ioutil and os package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a main function and in that function read a file named myfile.txt using ioutil.ReadFile function from ioutil package.

  • Step 3 − If an error is obtained while reading the file, print the error on the console and return.

  • Step 4 − The print statement is executed using fmt.Println()

Example

In this example we will use io.ReadFile function from io package to execute the program. Let’s see how its executed.

package main
import (
   "fmt"
   "io/ioutil"
)

func main() {
   // Read the contents of the file into a byte slice
   data, err := ioutil.ReadFile("myfile.txt")
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }

   // Convert the byte slice to a string
   mystr := string(data)

   // Print the contents of the file
   fmt.Println(mystr)
}

Output

When program is executed successfully
Hello alexa!

When program is not executed successfully
Error reading file: open file.txt: no such file or directory

Method 2: Using os package

In this illustration, the file is opened for reading using the os.Open method. Using the file.Read method, the contents of the file are read into a byte slice of data. When a file is no longer required, it is closed using the defer keyword and close method. The contents of the file are then written to the console using fmt.Println after the byte slice has been transformed to a string using the string function.

Syntax

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.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), io/ioutil and os package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Use the os.Open function in the main function to read from the file mentioned in the program.

  • Step 3 − Verify to see if there was a problem opening the file. Print an error message and exit the function if an error occurred.

  • Step 4 − Then, make sure the file is closed after it is no longer required by using the defer keyword and close method.

  • Step 5 − Using the file.Read() method, read the contents into byte-slice data.

  • Step 6 − Check to see if there was a problem reading the file. Print an error message and exit the function if an error occurred.

  • Step 7 − Use the string function to transform the byte slice data into a string str.

  • Step 8 − To print the contents of the file represented in the string str to the console, use the fmt.Println

Example

In this example we will use os package functions to execute the program.

package main
import (
   "fmt"
   "os"
)

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

   // Read the contents of the file into a byte slice
   data := make([]byte, 1024)
   n, err := myfile.Read(data)
   if err != nil {
      fmt.Println("Error reading file:", err)
      return
   }

   // Convert the byte slice to a string
   str := string(data[:n])

   // Print the contents of the file
   fmt.Println(str)
}

Output

When program is executed successfully
Hello alexa!

When program is not executed successfully
Error reading file: open file.txt: no such file or directory

Conclusion

We executed the program of creating strings from contents of a file using two methods. In the first example we used io/ioutil package and in the second example we used os package to execute the program.

Updated on: 22-Feb-2023

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements