From e66ab154bc59b7dd7e6ccb5aa9e6784f52c01e3f Mon Sep 17 00:00:00 2001 From: ggymm <1967988842@qq.com> Date: Thu, 24 Aug 2023 16:36:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E8=A6=86=E7=9B=96=E5=86=99=E5=85=A5?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2=E5=88=B0=E6=96=87=E4=BB=B6=E9=97=AE?= =?UTF-8?q?=E9=A2=98=20(#128)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fileutil/file.go | 6 ++++-- fileutil/file_test.go | 24 +++++++++++++++++------- 2 files changed, 21 insertions(+), 9 deletions(-) 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) {