diff --git a/fileutil/file.go b/fileutil/file.go index 6d2752c..3a043dc 100644 --- a/fileutil/file.go +++ b/fileutil/file.go @@ -594,9 +594,11 @@ func WriteCsvFile(filepath string, records [][]string, append bool) error { // WriteStringToFile write string to target file. // Play: https://go.dev/play/p/GhLS6d8lH_g func WriteStringToFile(filepath string, content string, append bool) error { - flag := os.O_RDWR | os.O_CREATE + var flag int if append { - flag = flag | os.O_APPEND + flag = os.O_RDWR | os.O_CREATE | os.O_APPEND + } else { + flag = os.O_RDWR | os.O_CREATE | os.O_TRUNC } f, err := os.OpenFile(filepath, flag, 0644) diff --git a/fileutil/file_test.go b/fileutil/file_test.go index b3f8b47..a4ae7a7 100644 --- a/fileutil/file_test.go +++ b/fileutil/file_test.go @@ -393,9 +393,7 @@ func TestWriteStringToFile(t *testing.T) { t.Fail() } - defer file.Close() - - err = WriteStringToFile(filepath, "hello", false) + err = WriteStringToFile(filepath, "hello world", false) if err != nil { t.Fail() } @@ -405,20 +403,32 @@ func TestWriteStringToFile(t *testing.T) { t.Fail() } + err = WriteStringToFile(filepath, "hello", false) + if err != nil { + t.Fail() + } + + content2, err := ReadFileToString(filepath) + if err != nil { + t.Fail() + } + err = WriteStringToFile(filepath, " world", true) if err != nil { t.Fail() } - content2, err := os.ReadFile(filepath) + content3, err := os.ReadFile(filepath) if err != nil { t.Fail() } - assert.Equal("hello", content1) - assert.Equal("hello world", string(content2)) + assert.Equal("hello world", content1) + assert.Equal("hello", content2) + assert.Equal("hello world", string(content3)) - os.Remove(filepath) + _ = file.Close() + _ = os.Remove(filepath) } func TestWriteBytesToFile(t *testing.T) {