Standard library / os
os.File.Truncate()
Changes file length without changing the sequential offset. Example uses a disposable temporary workspace. Expected stdout: '3 1\n'.
Formal Syntax & Structure
go syntaxgo
func (f *File) Truncate(size int64) errorParameters & Attributes
| Name | Type | Description |
|---|---|---|
| size | int64 | New length in bytes. |
Return Value
error
Changes file length without changing the sequential offset.
Working Example
Example Snippetgo
package main
import ( "fmt" "io" "os")
func check(e error) { if e != nil { panic(e) }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func opened() *os.File { seed(); f, e := os.OpenFile("a.txt", os.O_RDWR, 0); check(e); return f }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()() f := opened() defer f.Close() _, e := f.Seek(3, io.SeekStart) check(e) check(f.Truncate(1)) p, e := f.Seek(0, io.SeekCurrent) check(e) i, e := f.Stat() check(e) fmt.Println(p, i.Size())}