iT邦幫忙

4

蠻可愛的golang #40 基本輸出入介紹之拷貝檔案

  • 分享至 

  • xImage
  •  
// 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 
開啟原始檔失敗!
拷貝檔案失敗!

能有效進行錯誤處理.


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
老鷹(eagle)
iT邦高手 1 級 ‧ 2014-08-25 16:19:14

為什麼沒有男主角哭

0
一級屠豬士
iT邦大師 1 級 ‧ 2014-08-25 16:45:20

今天放假一天.

我要留言

立即登入留言