1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
file.go 2.54 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-11-02 11:40 . file write
package file
import (
"io"
"os"
"path/filepath"
)
func IsFile(f string) bool {
return IsDir(f) == 0
}
// DirEmpty 目录是否为空
func DirEmpty(path string) bool {
fs, e := filepath.Glob(filepath.Join(path, "*"))
if e != nil {
return false
}
if len(fs) > 0 {
return false
}
return true
}
func IsDir(f string) int {
fi, e := os.Stat(f)
if e != nil {
return -1
}
if fi.IsDir() {
return 1
}
return 0
}
// IsExist 文件或目录
func IsExist(f string) bool {
_, err := os.Stat(f)
return err == nil || os.IsExist(err)
}
// CopyFile is used to copy a file
func CopyFile(old, new string) error {
// Open the file and create a new one
r, err := os.Open(old)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(new)
if err != nil {
return err
}
defer w.Close()
// Copy the content
_, err = io.Copy(w, r)
if err != nil {
return err
}
return nil
}
func ReadFile(f *os.File) ([]byte, error) {
var size int
if info, err := f.Stat(); err == nil {
size64 := info.Size()
if int64(int(size64)) == size64 {
size = int(size64)
}
}
size++ // one byte for final read at EOF
// If a file claims a small size, read at least 512 bytes.
// In particular, files in Linux's /proc claim size 0 but
// then do not work right if read in small pieces,
// so an initial read of 1 byte would not work correctly.
if size < 512 {
size = 512
}
return Read(f, size)
}
func Read(f io.Reader, size int) ([]byte, error) {
if size < 0 {
return nil, io.ErrShortBuffer
}
data := make([]byte, 0, size)
for {
if len(data) >= cap(data) {
d := append(data[:cap(data)], 0)
data = d[:len(data)]
}
n, err := f.Read(data[len(data):cap(data)])
data = data[:len(data)+n]
if err != nil {
if err == io.EOF {
err = nil
}
return data, err
}
}
}
func CopyN(writer io.Writer, src io.Reader, size int64) (int64, error) {
const kSize int64 = 4096
var total int64 = 0
for total < size {
if size > kSize {
size = kSize
}
n, err := io.CopyN(writer, src, size)
if err != nil {
return 0, err
}
total += n
}
return total, nil
}
func Write(filename string, src io.Reader, perm os.FileMode) error {
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
defer f.Close()
_, err = io.Copy(f, src)
return err
}
func Open(filename string) (*os.File, int64, error) {
src, err := os.Open(filename)
if err != nil {
return nil, 0, err
}
stat, err := src.Stat()
if err != nil {
src.Close()
return nil, 0, err
}
return src, stat.Size(), nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.5.8

搜索帮助