(filePath string, content string, isOverWrite bool)
| 115 | } |
| 116 | |
| 117 | func writeToFile(filePath string, content string, isOverWrite bool) (err error) { |
| 118 | |
| 119 | if filePath == "" { |
| 120 | return errors.New("文件路径不能为空!") |
| 121 | } |
| 122 | |
| 123 | // 替换当前用户目录 |
| 124 | if filePath[0] == '~' { |
| 125 | home, _ := os.UserHomeDir() |
| 126 | if home != "" { |
| 127 | filePath = filepath.Join(home, filePath[1:]) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // 文件是否存在 |
| 132 | if !IsExist(filePath) { |
| 133 | |
| 134 | // 文件夹是否存在 |
| 135 | dirPath := filepath.Dir(filePath) |
| 136 | if dirPath != "" && !IsExist(dirPath) { |
| 137 | err := os.MkdirAll(dirPath, os.ModePerm) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | // 创建文件 |
| 144 | f, err := os.Create(filePath) |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | defer f.Close() |
| 149 | } |
| 150 | |
| 151 | // 文件内容 |
| 152 | if isOverWrite { |
| 153 | err = os.WriteFile(filePath, []byte(content), 0644) |
| 154 | } else { // 附加到文件中 |
| 155 | // 以只写的模式,打开文件 |
| 156 | f, err := os.OpenFile(filePath, os.O_WRONLY, 0644) |
| 157 | if err != nil { |
| 158 | return err |
| 159 | } |
| 160 | // 查找文件末尾的偏移量 |
| 161 | n, _ := f.Seek(0, os.SEEK_END) |
| 162 | // 从末尾的偏移量开始写入内容 |
| 163 | _, err = f.WriteAt([]byte(content), n) |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | defer f.Close() |
| 168 | } |
| 169 | |
| 170 | return err |
| 171 | } |
| 172 | |
| 173 | var totalSize float64 |
| 174 |
no test coverage detected