answer/pkg/dir/dir.go

51 lines
1.4 KiB
Go
Raw Normal View History

2022-09-27 17:59:05 +08:00
package dir
2022-11-11 11:53:44 +08:00
import (
"fmt"
"os"
"path/filepath"
)
2022-09-27 17:59:05 +08:00
func CreateDirIfNotExist(path string) error {
return os.MkdirAll(path, os.ModePerm)
2022-09-27 17:59:05 +08:00
}
2022-10-12 11:14:20 +08:00
func CheckDirExist(path string) bool {
f, err := os.Stat(path)
return err == nil && f.IsDir()
}
func CheckFileExist(path string) bool {
f, err := os.Stat(path)
return err == nil && !f.IsDir()
2022-10-12 11:14:20 +08:00
}
2022-11-11 11:53:44 +08:00
func DirSize(path string) (int64, error) {
var size int64
err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if !info.IsDir() {
size += info.Size()
}
return err
})
return size, err
}
func FormatFileSize(fileSize int64) (size string) {
if fileSize < 1024 {
//return strconv.FormatInt(fileSize, 10) + "B"
return fmt.Sprintf("%.2f B", float64(fileSize)/float64(1))
} else if fileSize < (1024 * 1024) {
return fmt.Sprintf("%.2f KB", float64(fileSize)/float64(1024))
} else if fileSize < (1024 * 1024 * 1024) {
return fmt.Sprintf("%.2f MB", float64(fileSize)/float64(1024*1024))
} else if fileSize < (1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2f GB", float64(fileSize)/float64(1024*1024*1024))
} else if fileSize < (1024 * 1024 * 1024 * 1024 * 1024) {
return fmt.Sprintf("%.2f TB", float64(fileSize)/float64(1024*1024*1024*1024))
} else { //if fileSize < (1024 * 1024 * 1024 * 1024 * 1024 * 1024)
return fmt.Sprintf("%.2f EB", float64(fileSize)/float64(1024*1024*1024*1024*1024))
}
}