golang 拷贝目录

在Go语言中,拷贝目录通常意味着要拷贝目录下的所有文件和子目录。Go标准库中并没有直接提供拷贝目录的函数,但可以通过组合使用标准库中的函数来实现这一功能。
以下是一个使用Go语言实现目录拷贝的示例代码:
package main

import (
“fmt”
“io”
“os”
“path/filepath”
)

// CopyFile copies a file from src to dst. If src and dst files exist, it will
// overwrite it.
func CopyFile(src, dst string) error {
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()

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

_, err = io.Copy(destinationFile, sourceFile)
return err
}

// CopyDir recursively copies a directory from src to dst.
func CopyDir(src, dst string) error {
// Get the properties of source dir
srcInfo, err := os.Stat(src)
if err != nil {
return err
}

// Create destination dir
if err = os.MkdirAll(dst, srcInfo.Mode()); err != nil {
return err
}

directory, _ := os.Open(src)
objects, err := directory.Readdir(-1)

for _, obj := range objects {
srcFullPath := filepath.Join(src, obj.Name())
dstFullPath := filepath.Join(dst, obj.Name())

if obj.IsDir() {
// Create sub-directories – recursively
if err = CopyDir(srcFullPath, dstFullPath); err != nil {
return err
}
} else {
// Perform the file copy
if err = CopyFile(srcFullPath, dstFullPath); err != nil {
return err
}
}
}
return nil
}

func main() {
src := “./srcDir” // source directory
dst := “./dstDir” // destination directory

err := CopyDir(src, dst)
if err != nil {
fmt.Println(“An error occurred while copying files:”, err)
return
}
fmt.Println(“Files copied successfully…”)
}
这段代码定义了两个函数:
CopyFile
和
CopyDir
。
CopyFile
用于拷贝单个文件,而
CopyDir
则递归地拷贝整个目录。
CopyFile
函数使用
io.Copy
来拷贝文件内容。
CopyDir
函数首先创建目标目录,然后遍历源目录中的所有文件和子目录,递归地拷贝它们。
在
main
函数中,你可以指定源目录和目标目录,然后调用
CopyDir
函数来执行拷贝操作。
请注意,这个示例代码没有处理所有可能的错误情况,例如权限问题、符号链接等,你可能需要根据你的具体需求调整代码。