package main import ( "fmt" "bufio" "io" "os" "flag" "strconv" ) // 定义一个结构体 type ReadWrite struct { In *string Out *string } // 定义初始化方法 func (rw *ReadWrite) Init() { rw.In = flag.String("in", "in", "in") rw.Out = flag.String("out", "out", "out") flag.Parse() } // 定义读文件的方法 func (rw *ReadWrite) Read() (result []int, err error) { file, err1 := os.Open(*(rw.In)) if nil != err1 { panic("error to open file...") } defer file.Close() br := bufio.NewReader(file) result = make([]int, 0) for { line, isPrefix, err2 := br.ReadLine() if nil != err2 { if io.EOF == err2 { fmt.Println("finish read ...") } break } if isPrefix { return } str := string(line) value, err3 := strconv.Atoi(str) if nil != err3 { err = err3 return } result = append(result, value) } return } // 定义写文件的方法 func (rw *ReadWrite) Write(value []int) { file, err := os.Create(*(rw.Out)) if nil != err { panic("error to create file...") } defer file.Close() for index, res := range value { str := strconv.Itoa(res*index) file.WriteString(str + "\n") } } func main() { defer func() { if ex:=recover();ex!=nil { fmt.Println(ex) } }() rw := new(ReadWrite) rw.Init() value, err := rw.Read() if nil != err { panic("error.....") } rw.Write(value) }
有疑问加站长微信联系(非本文作者)