Skip to content

Commit b7b06e0

Browse files
committed
os: Truncate on Windows will not create a new file
Truncating a non existent file 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 b7b06e0

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-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: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1335,6 +1335,33 @@ func TestTruncate(t *testing.T) {
13351335
}
13361336
}
13371337

1338+
func TestTruncateNonExistenceFile(t *testing.T) {
1339+
t.Parallel()
1340+
1341+
nonExistenceFileName := "./ThisFileDoesNotExist"
1342+
err := os.Truncate(nonExistenceFileName, 1)
1343+
if err == nil {
1344+
t.Error("Expect an error when truncating a non-existence file")
1345+
}
1346+
if !os.IsNotExist(err) {
1347+
t.Error("The error's Err field is not set properly")
1348+
}
1349+
1350+
pathErr, ok := err.(*os.PathError)
1351+
if !ok {
1352+
t.Errorf("Incorrect error type, got %T, want *os.PathError", err)
1353+
}
1354+
if pathErr.Path != nonExistenceFileName {
1355+
t.Errorf("Incorrect error file path, got %s, want %s", pathErr.Path, nonExistenceFileName)
1356+
}
1357+
1358+
// Truncate shouldn't create any new file.
1359+
if file, err := os.Open(nonExistenceFileName); (file != nil && err == nil) || !os.IsNotExist(err) {
1360+
file.Close()
1361+
t.Error("Truncating a non existence file should not create a new file")
1362+
}
1363+
}
1364+
13381365
// Use TempDir (via newFile) to make sure we're on a local file system,
13391366
// so that timings are not distorted by latency and caching.
13401367
// On NFS, timings can be off due to caching of meta-data on

0 commit comments

Comments
 (0)