How to Truncate a File in Golang?


In some cases, it might be necessary to reduce the size of a file by removing the data at the end of it. This process is called truncation. In Golang, truncating a file can be accomplished using the Truncate method provided by the os package. This method changes the size of the file to the specified length, effectively removing any data beyond that point.

In this article, we will discuss how to truncate a file in Golang.

Truncating a File in Golang

To truncate a file in Golang, you need to perform the following steps −

  • Open the file using the os.OpenFile method. This method takes the name of the file and a set of flags that specify how the file should be opened. To truncate a file, you should pass the os.O_RDWR flag, which allows you to read and write to the file.

file, err := os.OpenFile("file.txt", os.O_RDWR, 0666)
if err != nil {
   // Handle error
}
defer file.Close()
  • Call the Truncate method on the file object, passing the new size of the file in bytes. Any data beyond this point will be removed from the file.

err = file.Truncate(1024)
if err != nil {
   // Handle error
}
  • If you want to verify that the file has been truncated to the correct length, you can use the Stat method to get information about the file. The Size field of the FileInfo object returned by Stat should be equal to the new size of the file.

fileInfo, err := file.Stat()
if err != nil {
   // Handle error
}
fmt.Println(fileInfo.Size()) // Output: 1024

Example

Here's the complete code −

package main

import (
   "fmt"
   "os"
)

func main() {
   file, err := os.OpenFile("file.txt", os.O_RDWR, 0666)
   if err != nil {
      // Handle error
   }
   defer file.Close()
   
   err = file.Truncate(1024)
   if err != nil {
      // Handle error
   }
   
   fileInfo, err := file.Stat()
   if err != nil {
      // Handle error
   }
   fmt.Println(fileInfo.Size()) // Output: 1024 
}

Output

1024

In this example, we opened a file named file.txt using the os.OpenFile method with the os.O_RDWR flag. We then truncated the file to a size of 1024 bytes using the Truncate method, and verified that the file size had been updated correctly using the Stat method.

Conclusion

Truncating a file can be useful when you need to remove data from the end of a file. In Golang, this can be accomplished using the Truncate method provided by the os package. By following the steps outlined in this article, you should be able to truncate a file in Golang with ease.

Updated on: 25-Apr-2023

739 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements