From c5908177a27e41a51c48862625aab93abf7f4b12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Sun, 22 May 2022 16:44:19 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=86=99=E5=85=A5=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E8=A6=86=E7=9B=96=E5=86=99=E5=85=A5=E4=B8=8E=E8=BF=BD?= =?UTF-8?q?=E5=8A=A0=E5=86=99=E5=85=A5=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + file.go | 40 ++++++++++++++++++++++++++++++++++------ 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index b941df8..32d6a63 100644 --- a/.gitignore +++ b/.gitignore @@ -19,4 +19,5 @@ .idea .vscode *_test.go +*.txt diff --git a/file.go b/file.go index 307aa2b..7f7dd86 100644 --- a/file.go +++ b/file.go @@ -44,12 +44,13 @@ func File(workDir string, filePath string) *fileOperate { // // Date : 12:24 2022/5/22 type fileOperate struct { - workDir string - filePath string - autoCreate bool - permission os.FileMode - openFlag int - fileHandler *os.File + workDir string + filePath string + autoCreate bool + permission os.FileMode + openFlag int + fileHandler *os.File + clearHasContent bool // 文件写入时, 清空现有内容(覆盖写入), 默认追加写入 } // IsExist 文件是否存在 @@ -75,6 +76,7 @@ func (f *fileOperate) IsExist() (bool, bool, error) { // Date : 12:28 2022/5/22 func (f *fileOperate) AutoCreate() *fileOperate { f.autoCreate = true + f.openFlag = f.openFlag | os.O_CREATE return f } @@ -95,11 +97,26 @@ func (f *fileOperate) Permission(fileModel os.FileMode) *fileOperate { // Date : 13:40 2022/5/22 func (f *fileOperate) SetOpenFlag(flagList ...int) *fileOperate { for _, flag := range flagList { + if flag == os.O_CREATE { + f.AutoCreate() + continue + } f.openFlag = f.openFlag | flag } return f } +// SetClearHasContentForWrite 设置覆盖写入文件内容 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 16:41 2022/5/22 +func (f *fileOperate) SetClearHasContentForWrite() *fileOperate { + f.clearHasContent = true + f.openFlag = f.openFlag | os.O_TRUNC + return nil +} + // Create 创建文件 // // Author : go_developer@163.com<白茶清欢> @@ -210,6 +227,17 @@ func (f *fileOperate) Write(content []byte) error { return errors.New("文件打开失败 : " + err.Error()) } } + if f.clearHasContent { + // 覆盖写入 + if err := os.Truncate(f.filePath, 0); nil != err { + return err + } + n, _ := f.fileHandler.Seek(0, io.SeekEnd) + + _, writeErr := f.fileHandler.WriteAt(content, n) + return writeErr + } + // 追加写入 _, writeErr := f.fileHandler.Write(content) return writeErr }