Go語言複製檔案

2022-01-24 05:34:05 字數 1857 閱讀 6891

在使用go開發專案的過程中,有時我們需要做一些複製檔案的功能,我們可以把它封裝成乙個函式,在以後每次需要用到該功能的時候直接呼叫封裝的函式即可。

如果是大檔案,我們可以使用os包,使用os.open()os.create()都可以獲取到檔案控制代碼(檔案指標),然後通過檔案控制代碼(檔案指標)的read()write()方法,按照位元組讀取和寫入來實現複製檔案的功能

對於大檔案,我們可以採用下面的方式

package main

import (

"io"

"log"

"os"

)func copyfile(srcfilename string, dstfilename string)

defer func()

}()//建立目標檔案,稍後會向這個目標檔案寫入拷貝內容

distfile, err := os.create(dstfilename)

if err != nil

defer func()

}()//定義指定長度的位元組切片,每次最多讀取指定長度

var tmp = make(byte, 1024*4)

//迴圈讀取並寫入

for else

} }}func main()

使用io包的copy方法也能實現檔案複製功能

package main

import (

"fmt"

"io"

"os"

)//自己編寫乙個函式,接收兩個檔案路徑 srcfilename dstfilename

func copyfile(dstfilename string, srcfilename string) (written int64, err error)

defer srcfile.close()

//開啟dstfilename

dstfile, err := os.openfile(dstfilename, os.o_wronly | os.o_create, 0755)

if err != nil

defer dstfile.close()

return io.copy(dstfile, srcfile)

}func main()

}

還可以使用下面的方法

package main

import (

"bufio"

"fmt"

"io"

"os"

)//自己編寫乙個函式,接收兩個檔案路徑 srcfilename dstfilename

func copyfile(dstfilename string, srcfilename string) (written int64, err error)

defer srcfile.close()

//通過srcfile,獲取到reader

reader := bufio.newreader(srcfile)

//開啟dstfilename

dstfile, err := os.openfile(dstfilename, os.o_wronly | os.o_create, 0666)

if err != nil

writer := bufio.newwriter(dstfile)

defer func() ()

return io.copy(writer, reader)

}func main()

}

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語言檔案操作

檔案的開啟和關閉 os.open 函式能夠開啟乙個檔案,返回乙個 file和乙個err。對得到的檔案例項呼叫close 方法能夠關閉檔案。為了防止檔案忘記關閉,我們通常使用defer註冊檔案關閉語句。讀取檔案 file.read read方法定義如下 func f file read b byte ...

go語言 檔案操作

os.open 函式能夠開啟乙個檔案,返回乙個 file和乙個err。對得到的檔案例項呼叫close 方法能夠關閉檔案。package main import fmt os func main 關閉檔案 file.close 為了防止檔案忘記關閉,我們通常使用defer註冊檔案關閉語句。read方法...