go复制文件,文件夹

在go中复制文件夹内容需要递归来一层层检查文件夹是否存在,不存在则创建文件。

package util

import (
	"fmt"
	"io"
	"os"
	"path"
)

type Duplication struct{
}

func New()*Duplication{
	return &Duplication{}
}


//文件复制
func (d *Duplication)File(src, dst string) error {
	var err error
	var srcfd *os.File
	var dstfd *os.File
	var srcinfo os.FileInfo

	if srcfd, err = os.Open(src); err != nil {
		return err
	}
	defer srcfd.Close()

	if dstfd, err = os.Create(dst); err != nil {
		return err
	}
	defer dstfd.Close()

	if _, err = io.Copy(dstfd, srcfd); err != nil {
		return err
	}
	if srcinfo, err = os.Stat(src); err != nil {
		return err
	}
	return os.Chmod(dst, srcinfo.Mode())
}

// 文件夹复制
func (d *Duplication)Dir(src string, dst string) error{
	var err error
	var fds []os.DirEntry
	var srcinfo os.FileInfo

	if srcinfo, err = os.Stat(src); err != nil {
		return err
	}

	if err = os.MkdirAll(dst, srcinfo.Mode()); err != nil {
		return err
	}

	//if fds, err = ioutil.ReadDir(src); err != nil {
	//	return err
	//}
	fds, err = os.ReadDir(src)
	if err != nil {
		return err
	}

	for _, fd := range fds {
		srcfp := path.Join(src, fd.Name())
		dstfp := path.Join(dst, fd.Name())

		if fd.IsDir() {
			if err = d.Dir(srcfp, dstfp); err != nil {
				fmt.Println(err)
			}
		} else {
			if err = d.File(srcfp, dstfp); err != nil {
				fmt.Println(err)
			}
		}
	}
	return nil
}

本文参考自https://blog.csdn.net/whatday/article/details/109709845?utm_medium=distribute.pc_relevant.none-task-blog-2defaultbaidujs_baidulandingword~default-5-109709845-blog-122420214.topnsimilarv1&spm=1001.2101.3001.4242.4&utm_relevant_index=8

posted @ 2022-09-21 17:52  悠悠听风  阅读(269)  评论(0编辑  收藏  举报