file_util.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package util
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. )
  8. func CopyFile(src, dst string) error {
  9. source, err := os.Open(src)
  10. if err != nil {
  11. return err
  12. }
  13. defer source.Close()
  14. destDir := filepath.Dir(dst)
  15. if err := os.MkdirAll(destDir, os.ModePerm); err != nil {
  16. return err
  17. }
  18. destination, err := os.Create(dst)
  19. if err != nil {
  20. return err
  21. }
  22. defer destination.Close()
  23. _, err = io.Copy(destination, source)
  24. return err
  25. }
  26. func CreateHardLink(target, linkName string) error {
  27. // 文件夹不存在则创建
  28. destDir := filepath.Dir(linkName)
  29. if err := os.MkdirAll(destDir, os.ModePerm); err != nil {
  30. return err
  31. }
  32. return os.Link(target, linkName)
  33. }
  34. func FileExists(filename string) bool {
  35. _, err := os.Stat(filename)
  36. return !os.IsNotExist(err)
  37. }
  38. func RemoveEmptyDir(path string) error {
  39. entries, err := os.ReadDir(path)
  40. if err != nil {
  41. return err
  42. }
  43. if len(entries) == 0 {
  44. return os.Remove(path)
  45. }
  46. return nil
  47. }
  48. func EnsureFileCreated0777(path string) error {
  49. if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
  50. return fmt.Errorf("create dir `%s` error: %v", filepath.Dir(path), err)
  51. }
  52. if _, err := os.OpenFile(path, os.O_CREATE, 0777); err != nil {
  53. return fmt.Errorf("create file `%s` error: %v", path, err)
  54. }
  55. err := os.Chmod(path, 0777)
  56. if err != nil {
  57. return fmt.Errorf("chmod file `%s` error: %v", path, err)
  58. }
  59. return nil
  60. }