Standard library / os

os.Truncate()

Changes named file size, discarding bytes if shortened or adding zero-filled bytes if extended. Example uses a disposable temporary workspace. Expected stdout: 'ab\n'.

Formal Syntax & Structure

go syntaxgo
func Truncate(name string, size int64) error

Parameters & Attributes

NameTypeDescription
namestringName or pathname of the target.
sizeint64New length in bytes.

Return Value

error

Changes named file size, discarding bytes if shortened or adding zero-filled bytes if extended.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os")
func check(e error) {  if e != nil {    panic(e)  }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  seed()  check(os.Truncate("a.txt", 2))  b, e := os.ReadFile("a.txt")  check(e)  fmt.Println(string(b))}
Go Reference