package attach import ( "io" "os" "b612.me/starlog" "github.com/spf13/cobra" ) var Cmd = &cobra.Command{ Use: "attach", Short: "合并多个文件", Long: "合并多个文件", Run: func(this *cobra.Command, args []string) { src, _ := this.Flags().GetStringArray("src") out, _ := this.Flags().GetString("out") if len(src) < 2 || out == "" { starlog.Criticalln("请输入至少2个输入路径,一个输出路径") os.Exit(1) } os.Exit(runAttach(src, out)) }, } func runAttach(src []string, out string) int { fpOut, err := os.Create(out) if err != nil { starlog.Errorln("Err:无法创建输出文件!", err) return 2 } defer fpOut.Close() for _, file := range src { fpFile, err := os.OpenFile(file, os.O_RDONLY, 0644) if err != nil { starlog.Errorln("Err:Cannot Openfile:", err) return 3 } stats, err := fpFile.Stat() if err != nil { starlog.Errorln("Err:Cannot Get File Stats:", err) return 4 } if stats.Size() == 0 { starlog.Warningf("文件:%s为空文件,跳过!\n", stats.Name()) continue } buf := make([]byte, 65535) sumAll := 0 for { n, err := fpFile.Read(buf) if err != nil && err != io.EOF { starlog.Errorln("Err:Error Occured While ReadFile:", err) fpFile.Close() return 5 } sumAll += n _, errW := fpOut.Write(buf[:n]) if errW != nil { starlog.Errorln("Error While Write Data to OutFile", errW) return 6 } starlog.StdPrintf([]starlog.Attr{starlog.FgGreen}, "文件%s,已完成:%.2f%%\r", stats.Name(), (float64(sumAll) / float64(stats.Size()) * 100.0000)) if err == io.EOF { starlog.StdPrintf([]starlog.Attr{starlog.FgGreen}, "文件:%v,已完成:100.00%% \n", stats.Name()) fpFile.Close() break } } } starlog.StdPrintln([]starlog.Attr{starlog.FgGreen}, "Ok!文件合并完成") return 0 } func init() { Cmd.Flags().StringArrayP("src", "s", []string{}, "源文件路径") Cmd.Flags().StringP("out", "o", "", "输出文件路径") }