go語言基礎 檔案拷貝 copy io包

2021-08-19 13:53:21 字數 1232 閱讀 9846

io包下有個方法copy,拷貝檔案這個比較複雜,go語言中有個更加簡單的方法,這個就了解下複製的過程就可以了

packagemain

import(

"fmt"

"os"

"io"

)funcmain()else

}//實現檔案的複製,返回值拷貝的資料總量,以及拷貝過程中產生的錯誤

funccopyfile(destname,srcname string)(int

,error)

defersrcfile.close()

destfile, err := os.openfile(destname,os.o_wronly

|os.o_create

,0777)

iferr != nil

deferdestfile.close()

//複製資料

bs := make( byte

, 1024)

count := 0

//每次實際讀入資料量

total :=0

// 用於統計讀取的資料總量

forelse iferr == io.eof

destfile.write(bs[:count])

total+=count

}returntotal, nil

}funccopyfile2(destname, srcname string)(int64

, error)

defersrcfile.close()

destfile,err:=os.openfile(destname,os.o_wronly

|os.o_create

,0777)

iferr!=nil

deferdestfile.close()

returnio.copy(destfile,srcfile)

}

Go語言基礎(十六) Go語言檔案操作

package main import fmt os bufio io ioutil 錯誤處理方法 func handle why string,e error func main handle 檔案讀取失敗!err fmt.println str fmt.println 檔案讀取完畢!讀檔案方式二...

go語言陣列的拷貝

go語言的陣列與c語言的資料有一點不太一樣的地方,go語言的賦值是值拷貝 package main import fmt func main var b ages b 0 fmt.println ages fmt.println b 輸出的結果是 1 2 3 5 2 2 3 5 要想使ages改變時...

go語言基礎 結構體的 型別和拷貝

結構體的型別 值型別 預設是深拷貝 結構體指標 packagemain import fmt typeperson2struct funcmain 淺拷貝 指標 p2 new person p3 p1 p1 person2 fmt.printf p n p1 0xc0420023e0 p2 p1 值...