Skip to content

Commit 636b6c3

Browse files
committed
os: avoid creating a new file in Truncate on Windows
Truncate() a non existent file on Windows currently creates a new blank file. This behavior is not consistent with other OSes where a file not found error would instead be returned. This change makes Truncate on Windows return a file-not-found error when the specified file doesn't exist, bringing the behavior consistent. New test cases have been added to prevent a regression. Fixes 58977
1 parent 3360be4 commit 636b6c3

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/os/file_windows.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ func (f *File) seek(offset int64, whence int) (ret int64, err error) {
160160
// Truncate changes the size of the named file.
161161
// If the file is a symbolic link, it changes the size of the link's target.
162162
func Truncate(name string, size int64) error {
163-
f, e := OpenFile(name, O_WRONLY|O_CREATE, 0666)
163+
f, e := OpenFile(name, O_WRONLY, 0666)
164164
if e != nil {
165165
return e
166166
}

src/os/os_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,26 @@ func TestTruncate(t *testing.T) {
13351335
}
13361336
}
13371337

1338+
func TestTruncateNonexistentFile(t *testing.T) {
1339+
t.Parallel()
1340+
1341+
assertPathError := func(t testing.TB, path string, err error) {
1342+
t.Helper()
1343+
if pe, ok := err.(*os.PathError); !ok || !os.IsNotExist(err) || pe.Path != path {
1344+
t.Errorf("got error: %v\nwant an ErrNotExist PathError with path %q", err, path)
1345+
}
1346+
}
1347+
1348+
path := filepath.Join(t.TempDir(), "nonexistent")
1349+
1350+
err := os.Truncate(path, 1)
1351+
assertPathError(t, path, err)
1352+
1353+
// Truncate shouldn't create any new file.
1354+
_, err = os.Stat(path)
1355+
assertPathError(t, path, err)
1356+
}
1357+
13381358
// Use TempDir (via newFile) to make sure we're on a local file system,
13391359
// so that timings are not distorted by latency and caching.
13401360
// On NFS, timings can be off due to caching of meta-data on

0 commit comments

Comments
 (0)