Open In App

How to Truncate a File in Golang?

In Go language, you are allowed to truncate the size of the file with the help of the Truncate() function. This function is used to truncate the size of the given file in the specified size.

Syntax:



func Truncate(name string, size int64) error

Example 1:




// Golang program to illustrate how to
// truncate the size of the given file
package main
  
import (
    "log"
    "os"
)
  
var (
    myfile *os.FileInfo
    e      error
)
  
func main() {
  // Truncate the size of the 
  // given file to 200 bytes 
  // Using Truncate() function
    err := os.Truncate("gfg.txt", 200)
    if err != nil {
        log.Fatal(err)
  
    }
}

Output:



Before:

After:

Example 2:




// Golang program to illustrate how to
// truncate the size of the given file
package main
  
import (
    "log"
    "os"
)
  
var (
    myfile *os.FileInfo
    e      error
)
  
func main() {
  // Truncate the size of the given 
  // file to 0 bytes or empty file
  // Using Truncate() function
    err := os.Truncate("gfg.txt",0)
    if err != nil {
        log.Fatal(err)
  
    }
}

Output:

Before:

After:

Example 3:




// Golang program to illustrate how to 
// truncate the size of the given file
package main
  
import (
    "log"
    "os"
)
  
var (
    myfile *os.FileInfo
    e      error
)
  
func main() {
  // Truncate the size of the 
  // given file to 300 bytes 
  // Using Truncate() function
    err := os.Truncate("/Users/anki/Documents/new_folder/bingo.txt", 300)
    if err != nil {
        log.Fatal(err)
  
    }
}

Output:

Before:

After:


Article Tags :