Skip to content

os: avoid creating a new file in Truncate on Windows #59085

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/os/file_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ func (f *File) seek(offset int64, whence int) (ret int64, err error) {
// Truncate changes the size of the named file.
// If the file is a symbolic link, it changes the size of the link's target.
func Truncate(name string, size int64) error {
f, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)
f, e := OpenFile(name, O_WRONLY, 0666)
if e != nil {
return e
}
Expand Down
20 changes: 20 additions & 0 deletions src/os/os_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,26 @@ func TestTruncate(t *testing.T) {
}
}

func TestTruncateNonexistentFile(t *testing.T) {
t.Parallel()

assertPathError := func(t testing.TB, path string, err error) {
t.Helper()
if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != path {
t.Errorf("got error: %v\nwant an ErrNotExist PathError with path %q", err, path)
}
}

path := filepath.Join(t.TempDir(), "nonexistent")

err := os.Truncate(path, 1)
assertPathError(t, path, err)

// Truncate shouldn't create any new file.
_, err = os.Stat(path)
assertPathError(t, path, err)
}

// Use TempDir (via newFile) to make sure we're on a local file system,
// so that timings are not distorted by latency and caching.
// On NFS, timings can be off due to caching of meta-data on
Expand Down