Files
the-way-to-go_ZH_CN/eBook/12.3.md
Kilua d1ae94dadd 修正12.3章中的提示 (#717)
* 修正12.3章中的提示

* 根据liuhm98的意见,重新对12.3章末尾的提示做了修正
2019-09-06 15:53:33 -07:00

46 lines
950 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 12.3 文件拷贝
如何拷贝一个文件到另一个文件?最简单的方式就是使用 io 包:
示例 12.10 [filecopy.go](examples/chapter_12/filecopy.go)
```go
// filecopy.go
package main
import (
"fmt"
"io"
"os"
)
func main() {
CopyFile("target.txt", "source.txt")
fmt.Println("Copy done!")
}
func CopyFile(dstName, srcName string) (written int64, err error) {
src, err := os.Open(srcName)
if err != nil {
return
}
defer src.Close()
dst, err := os.Create(dstName)
if err != nil {
return
}
defer dst.Close()
return io.Copy(dst, src)
}
```
注意 `defer` 的使用当打开dst文件时发生了错误那么 `defer` 仍然能够确保 `src.Close()` 执行。如果不这么做src文件会一直保持打开状态并占用资源。
## 链接
- [目录](directory.md)
- 上一节:[文件读写](12.2.md)
- 下一节:[从命令行读取参数](12.4.md)