write.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright 2025 BackendServerTemplate Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package fileutils
  5. import (
  6. "github.com/SongZihuan/BackendServerTemplate/tool/utils/cleanstringutils"
  7. "os"
  8. "strings"
  9. )
  10. func Write(filePath string, dat string) error {
  11. // 尝试打开文件
  12. file, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  13. if err != nil {
  14. return err
  15. }
  16. defer func() {
  17. _ = file.Close()
  18. }()
  19. _, err = file.Write([]byte(dat))
  20. return err
  21. }
  22. func AppendOnExistsFile(filePath string, dat string) error {
  23. // 尝试打开文件(若文件不存在则返回错误)
  24. file, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY, 0644)
  25. if err != nil {
  26. return err
  27. }
  28. defer func() {
  29. _ = file.Close()
  30. }()
  31. _, err = file.Write([]byte(dat))
  32. return err
  33. }
  34. // CheckFileByLine 检查文件每一行,若fn返回 true 则本函数返回 true,否则返回false。
  35. // 传入 fn 的字符串不以 \n 结尾,空字符串也会传入
  36. func CheckFileByLine(filePath string, fn func(string) bool) (bool, error) {
  37. dat, err := os.ReadFile(filePath)
  38. if err != nil {
  39. return false, err
  40. }
  41. fileLine := strings.Split(cleanstringutils.GetString(string(dat)), "\n")
  42. for _, l := range fileLine {
  43. if fn(l) {
  44. return true, nil
  45. }
  46. }
  47. return false, nil
  48. }