Skip to content

Commit d6e73b4

Browse files
archie2xdeadprogram
authored andcommitted
add os.Truncate(name, size) (see #4209)
See https://pkg.go.dev/os#Truncate
1 parent 2e76cd3 commit d6e73b4

File tree

2 files changed

+24
-13
lines changed

2 files changed

+24
-13
lines changed

src/os/file_unix.go

+14-8
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ func NewFile(fd uintptr, name string) *File {
5555
return &File{&file{handle: unixFileHandle(fd), name: name}}
5656
}
5757

58+
// Truncate changes the size of the named file.
59+
// If the file is a symbolic link, it changes the size of the link's target.
60+
// If there is an error, it will be of type *PathError.
61+
func Truncate(name string, size int64) error {
62+
e := ignoringEINTR(func() error {
63+
return syscall.Truncate(name, size)
64+
})
65+
if e != nil {
66+
return &PathError{Op: "truncate", Path: name, Err: e}
67+
}
68+
return nil
69+
}
70+
5871
func Pipe() (r *File, w *File, err error) {
5972
var p [2]int
6073
err = handleSyscallError(syscall.Pipe2(p[:], syscall.O_CLOEXEC))
@@ -134,14 +147,7 @@ func (f *File) Truncate(size int64) (err error) {
134147
return ErrClosed
135148
}
136149

137-
e := ignoringEINTR(func() error {
138-
return syscall.Truncate(f.name, size)
139-
})
140-
141-
if e != nil {
142-
return &PathError{Op: "truncate", Path: f.name, Err: e}
143-
}
144-
return
150+
return Truncate(f.name, size)
145151
}
146152

147153
// ReadAt reads up to len(b) bytes from the File starting at the given absolute offset.

src/os/file_windows.go

+10-5
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ func (f *unixFileHandle) Truncate(size int64) error {
6363
return ErrNotImplemented
6464
}
6565

66+
// Truncate changes the size of the named file.
67+
// If the file is a symbolic link, it changes the size of the link's target.
68+
func Truncate(name string, size int64) error {
69+
return &PathError{Op: "truncate", Path: name, Err: ErrNotImplemented}
70+
}
71+
6672
func tempDir() string {
6773
n := uint32(syscall.MAX_PATH)
6874
for {
@@ -110,14 +116,13 @@ func (f unixFileHandle) Sync() error {
110116
return ErrNotImplemented
111117
}
112118

119+
// Truncate changes the size of the named file.
120+
// If the file is a symbolic link, it changes the size of the link's target.
113121
func (f *File) Truncate(size int64) error {
114-
var err error
115122
if f.handle == nil {
116-
err = ErrClosed
117-
} else {
118-
err = ErrNotImplemented
123+
return &PathError{Op: "truncate", Path: f.name, Err: ErrClosed}
119124
}
120-
return &PathError{Op: "truncate", Path: f.name, Err: err}
125+
return Truncate(f.name, size)
121126
}
122127

123128
// isWindowsNulName reports whether name is os.DevNull ('NUL') on Windows.

0 commit comments

Comments
 (0)