首页 > 代码库 > golang 读写文件
golang 读写文件
package mainimport ( "bufio" "flag" "fmt" "io" "os" "strconv")var infile *string = flag.String("i", "infile", "File contains values for sorting")var outfile *string = flag.String("o", "outfile", "File to receive sorted values")var algorithm *string = flag.String("a", "qsort", "Sort algorithm")func main() { flag.Parse() if infile != nil { fmt.Println("infile = ", *infile, "outfile = ", *outfile, "algorithm = ", *algorithm) } file, err := os.Open(*infile) if err != nil { fmt.Println("Failed to open the input file ", *infile) return } defer file.Close() br := bufio.NewReader(file) values := make([]int, 0) for { line, isPrefix, err1 := br.ReadLine() if err1 != nil { if err1 != io.EOF { err = err1 } break } if isPrefix { fmt.Println("A too long line,seems unexpected.") return } str := string(line) value, err1 := strconv.Atoi(str) if err1 != nil { err = err1 return } values = append(values, value) } wfile, ferr := os.Create(*outfile) if ferr != nil { fmt.Println("Failed to create the output file", *outfile) return } defer wfile.Close() length := len(values) for i := 0; i < length; i++ { for j := i; j < length; j++ { if values[i] > values[j] { values[i], values[j] = values[j], values[i] } } wfile.WriteString(strconv.Itoa(values[i]) + "\n") }}
golang 读写文件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。