1. 程式人生 > >Go終端讀寫

Go終端讀寫

壓縮文件 run one 數量 form package markdown json數據 clas

終端讀寫

操作終端相關文件句柄常量

os.Stdin:標準輸入

os.Stdout:標準輸出

os.Stderr:標準錯誤輸出

終端讀寫實例:

package main

import (
    "fmt"
)

var (
    firstName, lastName, s string
    i                      int
    f                      float32
    input                  = "greg / 20 / 0.8"
    format                = "%s / %d / %f"
)

type
student struct { Name string Age int Score float32 } func main() { fmt.Println("Please enter your full name: ") fmt.Scanln(&firstName, &lastName) // fmt.Scanf("%s %s", &firstName, &lastName) fmt.Printf("Hi %s %s!\n", firstName, lastName) fmt.Sscanf(input, format, &s, &i, &f) fmt.Println("From the string we read: "
, s, i, f) //greg 20 0.8 var str = "greg 18 89.92" var stu student fmt.Sscanf(str, "%s %d %f", &stu.Name, &stu.Age, &stu.Score) fmt.Println(stu) }

帶緩沖區的讀寫:

package main

import (
   "bufio"
   "fmt"
   "os"
)

var inputReader *bufio.Reader
var input string
var err error

func
main() { inputReader = bufio.NewReader(os.Stdin) reader := bufio.NewReader(os.Stdin) fmt.Println(">>>Please enter: ") str, err := reader.ReadString(‘\n‘) if err != nil { fmt.Println("read string failed, err:", err) return } fmt.Printf(">>>reader:%s\n", str) input, err = inputReader.ReadString(‘\n‘) if err == nil { fmt.Printf(">>>readstring:%s\n", input) } }

終端讀文件

package main

import (
   "bufio"
   "fmt"
   "os"
)

func main() {
   file, err := os.Open("D:/123.txt")
   if err != nil {
      fmt.Println("read file err:", err)
      return
   }
   defer file.Close()
   
   reader := bufio.NewReader(file)
   str, err := reader.ReadString(‘\n‘)
   if err != nil {
      fmt.Println("read string failed, err:", err)
      return
   }

   fmt.Printf("read str succ, ret:%s\n", str)
}

終端寫文件

從終端讀取一行字符串,統計英文、數字、空格以及其他字符的數量。

package main

import (
   "bufio"
   "fmt"
   "io"
   "os"
)

type CharCount struct {
   ChCount    int
   NumCount   int
   SpaceCount int
   OtherCount int
}

func main() {
   file, err := os.Open("D:/id_sra")
   if err != nil {
      fmt.Println("read file err:", err)
      return
   }
   defer file.Close()

   var count CharCount

   reader := bufio.NewReader(file)
   for {
      str, err := reader.ReadString(‘\n‘)
      if err == io.EOF {
         break
      }
      if err != nil {
         fmt.Printf("read file failed, err:%v", err)
         break
      }

      runeArr := []rune(str)
      for _, v := range runeArr {
         switch {
         case v >= ‘a‘ && v <= ‘z‘:
            fallthrough
         case v >= ‘A‘ && v <= ‘Z‘:
            count.ChCount++
         case v == ‘ ‘ || v == ‘\t‘:
            count.SpaceCount++
         case v >= ‘0‘ && v <= ‘9‘:
            count.NumCount++
         default:
            count.OtherCount++
         }
      }
   }

   fmt.Printf("char count:%d\n", count.ChCount)
   fmt.Printf("num count:%d\n", count.NumCount)
   fmt.Printf("space count:%d\n", count.SpaceCount)
   fmt.Printf("other count:%d\n", count.OtherCount)
}

文件讀取

os.File封裝所有文件相關操作,os.Stdin,os.Stdout, os.Stderr都是*os.File

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

func main() {
    inputFile, err := os.Open("input.txt")
    if err != nil {
        fmt.Printf("open file err:%v\n", err)
        return
    }
    defer inputFile.Close()

    inputReader := bufio.NewReader(inputFile)
    for {
        inputString, readerError := inputReader.ReadString(‘\n‘)
        if readerError == io.EOF {
            return
        }
        fmt.Printf("The input was: %s", inputString)
    }
}

greg@greg:day71$ vim input.txt
greg@greg:day71$ go run buffile.go 
The input was: 123456
The input was: asdf
The input was: 12390

讀取整個文件ioutil

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    inputFile := "input.txt"
    outputFile := "input_copy2.txt"
    buf, err := ioutil.ReadFile(inputFile)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
        return
    }

    fmt.Printf("%s\n", string(buf))
    err = ioutil.WriteFile(outputFile, buf, 0755)
    if err != nil {
        panic(err.Error())
    }
}

讀取壓縮文件gz

package main

import (
   "bufio"
   "compress/gzip"
   "fmt"
   "os"
)
func main() {
   fName := "MyFile.gz"
   var r *bufio.Reader
   fi, err := os.Open(fName)
   if err != nil {
      fmt.Fprintf(os.Stderr, "%v, Can’t open %s: error: %s\n", os.Args[0], fName, err)
      os.Exit(1)
   }

   defer fi.Close()

   fz, err := gzip.NewReader(fi)
   if err != nil {
      fmt.Fprintf(os.Stderr, "open gzip failed, err: %v\n", err)
      return
   }
   r = bufio.NewReader(fz)
   for {
      line, err := r.ReadString(‘\n‘)
      if err != nil {
         fmt.Println("Done reading file")
         os.Exit(0)
      }
      fmt.Println(line)
   }
}

文件寫入

os.OpenFile(“output.dat”,  os.O_WRONLY|os.O_CREATE, 0666)
第二個參數:文件打開模式:
os.O_WRONLY:只寫
os.O_CREATE:創建文件
os.O_RDONLY:只讀
os.O_RDWR:讀寫
os.O_TRUNC :清空
第三個參數:權限控制:
r ——> 004
w——> 002
x——> 001

文件寫入實例

package main

import (
   "bufio"
   "fmt"
   "os"
)

func main() {
   outputFile, outputError := os.OpenFile("output.dat",
      os.O_WRONLY|os.O_CREATE, 0666)
   if outputError != nil {
      fmt.Printf("An error occurred with file creation\n")
      return
   }

   defer outputFile.Close()
   outputWriter := bufio.NewWriter(outputFile)
   outputString := "hello world!\n"
   for i := 0; i < 10; i++ {
      outputWriter.WriteString(outputString)
   }
   outputWriter.Flush()//緩存區寫入到磁盤
}

拷貝文件

package main

import (
   "fmt"
   "io"
   "os"
)

func main() {
   CopyFile("target.txt", "source.txt")
   fmt.Println("Copy done!")
}

func CopyFile(dstName, srcName string) (written int64, err error) {
   src, err := os.Open(srcName)
   if err != nil {
      return
   }
   defer src.Close()

   dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0755)
   if err != nil {
      return
   }
   defer dst.Close()
   return io.Copy(dst, src)
}

命令行參數

os.Args是一個string的切片,用來存儲所有的命令行參數

package main

import (
    "fmt"
    "os"
    "strconv"
)

func add(m, n int) int {
    return m + n
}

func sub(m, n int) int {
    return m - n
}

func comp(m,n int) int {
    return m * n
}

func div(m,n int) int {
    return m/n
}

func main() {
    funcmap := map[string]func(int, int) int{
        "+": add,
        "-": sub,
        "*":comp,
        "/":div,
    }

    m, _ := strconv.Atoi(os.Args[1])
    n, _ := strconv.Atoi(os.Args[3])

    f := funcmap[os.Args[2]]
    if f != nil {
        fmt.Println(f(m, n))
        }
}

flag包的使用,用來解析命令行參數:

package main

import (
   "flag"
   "fmt"
)

func main() {
   var confPath string
   var logLevel int
   flag.StringVar(&confPath, "c", "", "please input conf path")
   flag.IntVar(&logLevel, "d", 10, "please input log level")
   flag.Parse()
   fmt.Println("path:", confPath)
   fmt.Println("log level:", logLevel)
}

greg@greg:flag$ ./flag -d 20
path: 
log level: 20
greg@greg:flag$ ./flag -d 100 -c /home/greg/go
path: /home/greg/go
log level: 100

帶緩沖區的文件讀寫

package main

import (
    "bufio"
    "flag"
    "fmt"
    "io"
    "os"
)

func cat(r *bufio.Reader) {
    for {
        buf, err := r.ReadString(‘\n‘)
        if err == io.EOF {
            break
        }
        fmt.Fprintf(os.Stdout, "%s", buf)
        //return
    }
}

func main(){
    flag.Parse()
    if flag.NArg() == 0 {
        cat(bufio.NewReader(os.Stdin))
    }
    for i := 0; i < flag.NArg(); i++ {
        f, err := os.Open(flag.Arg(i))
        fmt.Println(i,f)
        if err != nil {
            fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n",
                os.Args[0], flag.Arg(i), err.Error())
        }
            cat(bufio.NewReader(f))
        continue
    }
}
/*
greg@greg:bufflag$ ./bufflag a.txt b.txt
0 &{0xc4200640f0}
a
aa
aaa
aaaa
1 &{0xc420064140}
b
bb
bbb
bbbb
*/

帶緩沖區的終端讀寫

package main

import (
   "bufio"
   "fmt"
   "os"
)

func main() {
   fmt.Fprintf(os.Stdout, "%s\n", "hello world! - unbuffered")
   buf := bufio.NewWriter(os.Stdout)
   fmt.Fprintf(buf, "%s\n", "hello world! - buffered")
   buf.Flush()
}

Json數據協議

Go終端讀寫