码迷,mamicode.com
首页 > 其他好文 > 详细

golang 读写文件

时间:2014-10-31 15:15:53      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   os   ar   for   sp   文件   

package main

import (
    "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 读写文件

标签:style   blog   io   color   os   ar   for   sp   文件   

原文地址:http://www.cnblogs.com/liyixin/p/4064878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!