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

Go终端读写

时间:2018-02-13 12:31:14      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:util   终端   只读   span   blog   src   flush   pac   core   

终端读写

操作终端相关文件句柄常量

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终端读写

标签:util   终端   只读   span   blog   src   flush   pac   core   

原文地址:https://www.cnblogs.com/gregoryli/p/8446282.html

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