// hello45
package main
import (
"fmt"
"io"
"os"
)
func CopyFile(src, tar string) (written int64, err error) {
srcf, err := os.Open(src)
if err != nil {
fmt.Println("開啟原始檔失敗!")
return
}
defer srcf.Close()
tarf, err := os.OpenFile(tar, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fmt.Println("建立目標檔失敗!")
return
}
defer tarf.Close()
return io.Copy(tarf, srcf)
}
func main() {
written, err := CopyFile("source.txt", "target.txt")
if err != nil {
fmt.Println("拷貝檔案失敗!")
return
}
fmt.Printf("拷貝檔案成功! 共處理 %d bytes\n", written)
}
執行過程:
[asami 15:42 hello45]λ ll
總計 2212
-rwxrwxr-x. 1 asami asami 2255568 2014-08-25 15:39 hello45
-rw-rw-r--. 1 asami asami 617 2014-08-25 15:39 hello45.go
-rw-rw-r--. 1 asami asami 36 2014-08-25 15:42 source.txt
[asami 15:42 hello45]λ ./hello45
拷貝檔案成功! 共處理 36 bytes
[asami 15:42 hello45]λ ll
總計 2216
-rwxrwxr-x. 1 asami asami 2255568 2014-08-25 15:39 hello45
-rw-rw-r--. 1 asami asami 617 2014-08-25 15:39 hello45.go
-rw-rw-r--. 1 asami asami 36 2014-08-25 15:42 source.txt
-rw-r--r--. 1 asami asami 36 2014-08-25 15:42 target.txt
順利完成拷貝檔案.
刪除文字檔案後測試.
[asami 15:46 hello45]λ rm *.txt
[asami 15:46 hello45]λ ll
總計 2208
-rwxrwxr-x. 1 asami asami 2255568 2014-08-25 15:39 hello45
-rw-rw-r--. 1 asami asami 617 2014-08-25 15:39 hello45.go
[asami 15:46 hello45]λ ./hello45
開啟原始檔失敗!
拷貝檔案失敗!
能有效進行錯誤處理.