標籤:檔案 使用者 UNC pre xxx highlight strong ring info
檔案的拷貝
package mainimport ("os""fmt""io")func main(){args := os.Argsif len(args) != 3{fmt.Println("必須是 xxx srcFile dstFile")return}srcFileName := args[1]dstFileName := args[2]srcFile,err1 := os.Open(srcFileName)dstFile,err2 := os.Create(dstFileName)if err1 !=nil{fmt.Println("err1=",err1)return}if err2 !=nil{fmt.Println("err2=",err2)}defer srcFile.Close()defer dstFile.Close()buf := make([]byte, 4*1024)for {n,err3:=srcFile.Read(buf)if err3!=nil{if err3==io.EOF{break}fmt.Println("err3=",err3)}dstFile.Write(buf[:n])}}
tcp傳輸檔案
//發送方package mainimport ("fmt""os""net""io")func sendFile(path string,conn net.Conn){//以唯讀方法開啟檔案f,_:=os.Open(path)defer f.Close()buf := make([]byte,1024*4)for {n,err:=f.Read(buf)if err!=nil{if err==io.EOF{fmt.Println("檔案發送完畢")return}fmt.Println("出錯了")return}conn.Write(buf[:n])}}func main() {//提示使用者輸入檔案路徑並擷取fmt.Println("請輸入要傳輸的檔案:")var path stringfmt.Scan(&path)//擷取檔案的名字fileInfo,err := os.Stat(path)if err!=nil{fmt.Println("err1=",err)return}fileName := fileInfo.Name()//主動串連伺服器conn,_:=net.Dial("tcp","localhost:8080")defer conn.Close()//給接收方先傳送檔案名conn.Write([]byte(fileName))//接收對方的回複,如果為ok,說明對方準備好,可以發檔案buf := make([]byte,1024)n,_:=conn.Read(buf)if string(buf[:n]) == "ok"{//發送內容sendFile(path,conn)}}//接收方package mainimport ("net""fmt""os""io")func recvFile(fileName string,conn net.Conn){f,_:=os.Create("mmp"+fileName)defer f.Close()for {buf:=make([]byte,1024)n,err :=conn.Read(buf)if err!=nil{if err ==io.EOF{fmt.Println("檔案接收完畢")return}}f.Write(buf[:n])}}func main(){listener,_:=net.Listen("tcp","localhost:8080")defer listener.Close()//阻塞等待使用者串連conn,_:=listener.Accept()buf:=make([]byte,1024)//先讀取對方發來的檔案名稱n,err:=conn.Read(buf)if err!=nil{fmt.Println("err=",err)return}fileName := string(buf[:n])conn.Write([]byte("ok"))recvFile(fileName,conn)}
go語言實現檔案的拷貝,網路間傳輸檔案