ssgf_utils/common_fun/file_func.go
2025-07-15 16:51:07 +08:00

36 lines
860 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cf
import (
"fmt"
"os"
"path/filepath"
)
// EnsureDirExists 确保目录存在,如果不存在则创建
func EnsureDirExists(dirPath string) error {
// 判断路径是否存在
_, err := os.Stat(dirPath)
if os.IsNotExist(err) {
// 目录不存在,递归创建
err = os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
return fmt.Errorf("创建目录失败,目录:%serr %w", dirPath, err)
}
} else if err != nil {
// 其他错误(如权限问题)
return fmt.Errorf("检查目录失败,目录:%serr %w", dirPath, err)
}
return nil
}
// EnsureParentDirExists 确保文件的目录存在,如果不存在则创建
func EnsureParentDirExists(filePath string) error {
// 提取父级目录路径
dir := filepath.Dir(filePath)
err := EnsureDirExists(dir)
if err != nil {
return err
}
return nil
}