Golang Program to open a file in the read-write mode without truncating the file


In this golang article, we are going to use os.OpenFile() and ioutil.Readfile() to append the given file without truncating it. In the first Example, we are going to Os.Openfile to access the file and then by using file.WriteString function we will append it. In the second Example, we will use ioutil,ReadFile(), ioutil.WriteFile() and Append() functions to perform the same operation on the file without truncating it 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.

os.Openfile()

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.

file.WriteString()

In Go programming language, WriteString method is used to write a string to a file. The string is passed as an argument in the function as str.

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.

ioutil.WriteFile()

In Go, WriteFile belongs to ioutil package and contains three parameters, the first is the filename where data is to be written, second is the data which is to be written and third is the file permission. The data is written to the file if function is executed successfully.

Method 1

In this method we will write a go language program to open a file in the read write mode without truncating the file by using various functions present in os package.

Algorithm

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

  • Then start the main() function. Inside the main() function call the OpenFile() function to open the provided file and pass the required arguments as the name of file along with flags to be used when opening the file (os.O_RDWR), and Unix-style permissions for the file as arguments to the function.

  • Check if there was an error opening the file. If so, print an error message on the screen. Use the file.Close() function in order to close the file.

  • Use the "file.WriteString" method to write a string of data to the end of the file. Check if there was an error writing to the file. If so, print an error message.

  • Use the "file.Seek" method to move the position in the file to the beginning. Use the "io.ReadAtLeast" method to read a specified number of bytes from the file.

  • Check if there was an error reading from the file. If so, print an error message. Otherwise print the data of the file.

Example

In the following Example, we will learn how to use OS package of Golang to open a file in read-write mode without truncating it.

package main

import (
   "fmt"
   "os"
)

func main() {
   // Open file in read-write mode without truncating it
   file, err := os.OpenFile("newfile.txt", os.O_RDWR, 0644)
   if err != nil {
      fmt.Println("Error opening file:", err)
      return
   }
   defer file.Close()

   // Write data to the file
   _, err = file.WriteString("Hello World!\n")
   if err != nil {
      fmt.Println("Error writing to file:", err)
      return
   }

   // Move the position in the file to the beginning
   _, err = file.Seek(0, 0)
   if err != nil {
      fmt.Println("Error seeking in file:", err)
      return
   }

   // Read data from the file
   data := make([]byte, 14)
   _, err = file.Read(data)
   if err != nil {
      fmt.Println("Error reading from file:", err)
      return
   }

   fmt.Println("Data read from file:", string(data))
}

Output

Data read from file: Hello World!

Method 2

In this method, we will write the go language program to open a file in the read write mode without truncating the file by using various functions present in ioutil package.

Algorithm

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

  • Then start the main() function. Inside the main() call the ReadFile() function present in the ioutil package to read the entire contents of the file into a byte slice.

  • Check if there was an error reading the file. If the error is received then we need toprint the error message on the screen.

  • Use the append() function to add data to the file specified.

  • Call the WriteFile() function and pass in the name of the file to be opened, the modified byte slice, and the Unix-style permissions for the file.

  • Check if there was an error writing to the file. If so, print an error message on the screen. Otherwise print that the data is read from the file.

Example

In the following Example,we are going to open a file in read-write mode, using ioutil package of golang.

package main

import (
   "fmt"
   "io/ioutil"
)

func main() {
   // Read data from the file
   data, err := ioutil.ReadFile("notepad.txt")
   if err != nil {
      fmt.Println("Error reading from file:", err)
      return
   }

   // Modify the data
   data = append(data, []byte("\nHello, World")...)

   // Write the modified data back to the file
   err = ioutil.WriteFile("notepad1.txt", data, 0644)
   if err != nil {
      fmt.Println("Error writing to file:", err)
      return
   }

   fmt.Println("Data read from the file.", string(data))
}

Output

Data read from the file.
Hello, World

Conclusion

We have successfully compiled and executed a go language program to open a file in read-write mode without truncating the file along with Examples.Here we have used two Examples to implement the result. In the first Example we are using the functions present in the os package while in the second Example we are using the ioutil package to implement the result. The "os" package provides more control over the file operations, while the "ioutil" package provides easier file operations with lesser code. Both Examples have their own advantages and can be used depending on the requirement of the application.

Updated on: 03-May-2023

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements