zoukankan      html  css  js  c++  java
  • golang 读写文件

    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]) + "
    ")
        }
    
    }
  • 相关阅读:
    一种client同步server数据的方案
    nodejs package.json解释
    node.js JS对象和JSON字符串之间的转换
    setInterval的用法
    ActiveMQ 入门Nodejs版
    ActiveMQ + NodeJS + Stomp 极简入门
    为什么 ++[[]][+[]]+[+[]] = 10?
    Child Process模块
    phantomjs 解码url
    PhantomJSのメモいろいろ
  • 原文地址:https://www.cnblogs.com/liyixin/p/4064878.html
Copyright © 2011-2022 走看看