Support O_TRUNC flag to MemMapFs.OpenFile

To truncate an existing file when opening.
This commit is contained in:
Alex Tomlins 2015-08-09 18:18:31 +01:00 committed by Alex Tomlins
parent 8d3d399d37
commit 4c9b319a33
2 changed files with 18 additions and 0 deletions

View File

@ -99,6 +99,17 @@ func TestOpenFile(t *testing.T) {
t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents)) t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents))
} }
f.Close() f.Close()
f, err = fs.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0600)
if err != nil {
t.Error(fs.Name(), "OpenFile (O_TRUNC) failed:", err)
continue
}
contents, _ = ioutil.ReadAll(f)
if string(contents) != "" {
t.Errorf("%v: expected truncated file, got: '%v'", fs.Name(), string(contents))
}
f.Close()
} }
} }

View File

@ -183,6 +183,13 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro
return nil, err return nil, err
} }
} }
if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 {
err = file.Truncate(0)
if err != nil {
file.Close()
return nil, err
}
}
return file, nil return file, nil
} }