github.com/metux/go-metabuild@v0.0.0-20240118143255-d9ed5ab697f9/util/fileutil/copy.go (about)

     1  package fileutil
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  )
     8  
     9  func CopyFile(src, dst string, mode os.FileMode) error {
    10  	sourceFileStat, err := os.Stat(src)
    11  	if err != nil {
    12  		return err
    13  	}
    14  
    15  	if !sourceFileStat.Mode().IsRegular() {
    16  		return fmt.Errorf("%s is not a regular file", src)
    17  	}
    18  
    19  	source, err := os.Open(src)
    20  	if err != nil {
    21  		return err
    22  	}
    23  	defer source.Close()
    24  
    25  	destination, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode)
    26  	if err != nil {
    27  		return err
    28  	}
    29  	defer destination.Close()
    30  
    31  	_, err = io.Copy(destination, source)
    32  	return err
    33  }