Golang program to append a string in an existing file


In Golang, we can use io and os packages to append a string in an existing file. file contains data that can be manipulated in many ways like editing and writing the data. In this article the first method will demonstrate the application of os.Open file of OS package. In the second method, we are going to demonstrate the application of io package.

Method 1: Using OS Package

In this method, we are going to use os.OpenFile function of OS package in Golang. The permissions for the file are specified by the 0644 parameters. The file will be created with the requested permissions if it doesn't already exist. Then, the string is subsequently written to the file using file.WriteString. Before printing a success message, we first examine the WriteString method's return values, which include the number of bytes written and an error.

Syntax

os.OpenFile

We use os.OpenFile to initially open the file. As indicated by the flags os.O APPEND and os.O WRONLY, respectively, we want to open the file for appending and writing.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), 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 open the file named file.txt for appending and writing using the following functions described in code below.

  • Step 3 − If an error persists while opening the file, print the error on the console and return.

  • Step 4 − Close the file using defer and close keyword.

  • Step 5 − Then, write the string defined to the file using WriteString method.

  • Step 6 − If an error persists while writing to the file print the error and return.

  • Step 7 − If the string is appended in the file successfully print the success message using fmt.Println() function.

Example

In this example, we will use os package functions to append a string.

package main
import (
   "fmt"
   "os"
)

func main() {
   // Open the file for appending
   myfile, err := os.OpenFile("file.txt", os.O_APPEND|os.O_WRONLY, 0644)
   if err != nil {
      fmt.Println(err)
      return
   }
   defer myfile.Close()

   // Write the string to the file
   _, err = myfile.WriteString("This is a new line.\n")
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println("The string was appended to the file successfully.")
}

Output

The string was appended to the file successfully.

Method 2: Using io/ioutil Package

In this method, we will use ioutil.ReadFile to read a file's contents into a byte slice. The byte slice is then changed into a string, added to the new data, and written back to the file using ioutil.WriteFile. Both Ioutil.ReadFile and ioutil.WriteFile can take care of the file's opening, closing, and error handling. They are frequently used for straightforward file operations, however os.OpenFile and manual file handling may be required for more involved activities.

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 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 the file1.txt using ioutil.ReadFile function.

  • Step 3 − If any error comes while reading the file print the error on the console and return.

  • Step 4 − Then, convert the file data to string and append the new string in that data.

  • Step 5 − Then, use ioutil.WriteFile function to write the data back to the file with new string.

  • Step 6 − If an error comes while writing data back to the file print the error and return.

  • Step 7 − Finally, if string is appended successfully print a success message with the help of fmt.Println() function where ln means new line.

Example

In this example, we will use io/ioutil package functions to append the string.

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

func main() {
   // Read the contents of the file into a byte slice
   data, err := ioutil.ReadFile("file1.txt")
   if err != nil {
      fmt.Println(err)
      return
   }
   // Convert the byte slice to a string and append the new string
   newData := string(data) + "This is a new line.\n"

   // Write the new data back to the file
   err = ioutil.WriteFile("file1.txt", []byte(newData), 0644)
   if err != nil {
      fmt.Println(err)
      return
   }
   fmt.Println("The string was appended to the file successfully.")
}

Output

The string was appended to the file successfully.

Conclusion

We executed the program of appending a string in an existing file using two methods. In the first method we used os package functions to execute the program and in the second method we used io/ioutil package.

Updated on: 22-Feb-2023

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements