From 4c9b319a3370196839c6d1fee73944f4cc968b5f Mon Sep 17 00:00:00 2001 From: Alex Tomlins Date: Sun, 9 Aug 2015 18:18:31 +0100 Subject: [PATCH] Support O_TRUNC flag to MemMapFs.OpenFile To truncate an existing file when opening. --- fs_test.go | 11 +++++++++++ memmap.go | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/fs_test.go b/fs_test.go index ffe9375..c9f2667 100644 --- a/fs_test.go +++ b/fs_test.go @@ -99,6 +99,17 @@ func TestOpenFile(t *testing.T) { t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents)) } 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() } } diff --git a/memmap.go b/memmap.go index 6e39320..56f3f46 100644 --- a/memmap.go +++ b/memmap.go @@ -183,6 +183,13 @@ func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, erro 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 }