golang 复制文件
在 Golang 中,可以使用 io 和 os 包中的函数来复制文件。以下是一个简单的示例:
package main
import (
"io"
"os"
)
func main() {
// 打开源文件
srcFile, err := os.Open("source.txt")
if err != nil {
panic(err)
}
defer srcFile.Close()
// 创建目标文件
dstFile, err := os.Create("destination.txt")
if err != nil {
panic(err)
}
defer dstFile.Close()
// 复制文件内容
_, err = io.Copy(dstFile, srcFile)
if err != nil {
panic(err)
}
// 刷新缓冲区
err = dstFile.Sync()
if err != nil {
panic(err)
}
}
在这个示例中,我们首先打开源文件和创建目标文件。然后,我们使用 io.Copy() 函数将源文件的内容复制到目标文件中。最后,我们使用 Sync() 函数刷新缓冲区。
请注意,在使用 os.Create() 创建目标文件时,如果目标文件已经存在,它将被覆盖。如果您不希望覆盖现有文件,可以使用 os.Open() 打开目标文件并将 os.O_CREATE 标志与 os.O_EXCL 标志一起使用,以确保在文件不存在时才创建目标文件
原文地址: https://www.cveoy.top/t/topic/fh1A 著作权归作者所有。请勿转载和采集!