Copy of File
Package Mainimport ("OS" "FMT" "IO") func main () {args: = os. Argsif len (args)! = 3{fmt. PRINTLN ("must be 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 Transfer files
Sender Package Mainimport ("FMT" "OS" "NET" "Io") func sendFile (path string,conn net. Conn) {//Open file F,_:=os as read-only method. 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 ("File sent Complete") return}fmt. Println ("wrong") return}conn. Write (Buf[:n])}}func main () {//Prompts the user to enter a file path and obtains the FMT. Println ("Please enter the file to transfer:") var path stringfmt. Scan (&path)//Get the name of the file Fileinfo,err: = OS. Stat (path) if err!=nil{fmt. Println ("err1=", err) Return}filename: = Fileinfo.name ()//Active connection to server conn,_:=net. Dial ("TCP", "localhost:8080") defer Conn. Close ()//Send the file name conn to the receiver first. Write ([]byte (FileName))//Receive each other's reply, if OK, indicate the other side is ready, you can send the file buf: = make ([]byte,1024) n,_:=conn. Read (BUF) if string (buf[:n] = = "OK" {//Send content Sendfile (path,conn)}}//receiver 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 ("File received complete") Return}}f.write (Buf[:n])}}func main () {listener,_:=net. Listen ("TCP", "localhost:8080") defer listener. Close ()//block waits for user to connect Conn,_:=listener. Accept () Buf:=make ([]byte,1024)//First read the file name 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 language to implement file copy, inter-network transfer files