向文件添加内容

packagemainimport("fmt""os")funcmain(){message:="Add this content at end"filename:="test.txt"f,err:=os.OpenFile(filename,os.O_RDWR|os.O_APPEND|os.O_CREATE,0660)iferr!=nil{fmt.Println(err)os.Exit(-1)}deferf.Close()fmt.Fprintf(f,"%s\n",message)}

压缩文件到ZIP格式

packagemainimport("archive/zip""fmt""io""log""os")funcappendFiles(filenamestring,zipw*zip.Writer)error{file,err:=os.Open(filename)iferr!=nil{returnfmt.Errorf("Failed to open %s: %s",filename,err)}deferfile.Close()wr,err:=zipw.Create(filename)iferr!=nil{msg:="Failed to create entry for %s in zip file: %s"returnfmt.Errorf(msg,filename,err)}if_,err:=io.Copy(wr,file);err!=nil{returnfmt.Errorf("Failed to write %s to zip: %s",filename,err)}returnnil}funcmain(){flags:=os.O_WRONLY|os.O_CREATE|os.O_TRUNCfile,err:=os.OpenFile("test.zip",flags,0644)iferr!=nil{log.Fatalf("Failed to open zip for writing: %s",err)}deferfile.Close()varfiles=[]string{"test1.txt","test2.txt","test3.txt"}zipw:=zip.NewWriter(file)deferzipw.Close()for_,filename:=rangefiles{iferr:=appendFiles(filename,zipw);err!=nil{log.Fatalf("Failed to add file %s to zip: %s",filename,err)}}}

读取ZIP文件里面的文件

packagemainimport("archive/zip""fmt""log""os")funclistFiles(file*zip.File)error{fileread,err:=file.Open()iferr!=nil{msg:="Failed to open zip %s for reading: %s"returnfmt.Errorf(msg,file.Name,err)}deferfileread.Close()fmt.Fprintf(os.Stdout,"%s:",file.Name)iferr!=nil{msg:="Failed to read zip %s for reading: %s"returnfmt.Errorf(msg,file.Name,err)}fmt.Println()returnnil}funcmain(){read,err:=zip.OpenReader("test.zip")iferr!=nil{msg:="Failed to open: %s"log.Fatalf(msg,err)}deferread.Close()for_,file:=rangeread.File{iferr:=listFiles(file);err!=nil{log.Fatalf("Failed to read %s from zip: %s",file.Name,err)}}}