終端、文件讀寫與json協議、錯誤處理

1、終端處理json

操做終端相關文件句柄常量ide

os.Stdin:標準輸入
os.Stdout:標準輸出
os.Stderr:標準錯誤輸出

一些方法spa

fmt.Println("")
fmt.Printf()
fmt.Scanln(&a, &b)
fmt.Scanf("%s %s",&a, &b)
fmt.Sscanf()
package main

import "fmt"

type Student struct{
    Name string
    Age int
    Score float32
}

func main(){
    var t = "bob 18 95.5"
    var stu Student
    fmt.Sscanf(t,"%s %d %f",&stu.Name, &stu.Age, &stu.Score)
    fmt.Println(stu)
}
Sscanf的使用

帶緩衝區的讀寫(解決磁盤IO問題)命令行

package main

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

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

func main(){
    input = bufio.NewReader(os.Stdin)
    val, err = input.ReadString('\n')
    if err == nil{
        fmt.Println(val)
    }
}
package main

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

type ctn struct{
    charctn  int
    numctn int
    spacectn int
    otherctn int
}

func main(){
    file, err := os.Open("E:/test/t1.txt")
    if err != nil{
        fmt.Println("read file faile")
        return
    }
    defer file.Close()
    reader := bufio.NewReader(file)
    var count ctn
    for {
        str, err := reader.ReadString('\n')
        if err == io.EOF{
            break
        }
        if err != nil{
            fmt.Println("read file faile")
            return
        }
        runArry := []rune(str)
        for _, v := range runArry{
            switch {
            case v > 'a' && v < 'z':
                fallthrough
            case v > 'A' && v < 'Z':
                count.charctn++
            case v == ' ' || v == '\t':
                count.spacectn++
            case v >= '0' && v <= '9':
                count.numctn++
            default:
                count.otherctn++
            }
        }
    }
    fmt.Println(count)
}
從文件讀取一行字符串,統計英文,數字,空格,其它的數量

2、文件讀寫code

os.File封裝全部文件相關操做,以前講的os.Stdin,os.Stdout,os.Stderr都是*os.File
打開一個文件進行操做:os.Open(name string) (*File, error)
關閉一個文件:File.Close()blog

package main

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

func main(){
    file := "E:/test/t1.txt"
    buf, err := ioutil.ReadFile(file)
    if err != nil{
        fmt.Fprintf(os.Stderr,"Error:%s",err)
        return
    }
    fmt.Printf("%s",string(buf))
}
package main

import (
    "bufio"
    "compress/gzip"
    "fmt"
    "os"
)

func main(){
    fName := "test.gz"
    var r *bufio.Reader
    fi, err := os.Open(fName)
    if err != nil{
        return
    }
    fz, err := gzip.NewReader(fi)
    if err != nil{
        return
    }
    r = bufio.NewReader(fz)
    for {
        line, err := r.ReadString('\n')
        if err != nil{
            return
        }
        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

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

package main

import (
    "fmt"
    "os"
)


func main(){
    fmt.Println(len(os.Args))
    for i, v := range os.Args{
        fmt.Println(i,v)
    }
}

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("logLevel", logLevel)
}

3、Json數據協議input

導入包:encoding/json
序列化:json.Marshal(data.interdace{})
反序列化:json.UnMarshal(data []byte, v interface{})
package main

import (
    "fmt"
    "encoding/json"
)
type Student struct{
    Name string
    Age int
}

func structTest() (ret string, er error){
    stu := Student{
        Name: "bob",
        Age: 18,
    }
    data, err := json.Marshal(stu)
    if err != nil{
        er = fmt.Errorf("err:%v",err)
        return
    }
    fmt.Println(string(data))
    ret = string(data)
    return 
}

func structTest2() {
    data, err := structTest()
    if err != nil{
        return
    }
    var stu Student
    err = json.Unmarshal([]byte(data), &stu)
    if err != nil{
        return
    }
    fmt.Println(stu)
}

func mapTest(){
    var m map[string]interface{}
    m = make(map[string]interface{})
    m["name"] = "bob"
    m["age"] = 18
    data, err := json.Marshal(m)
    if err != nil{
        return
    }
    fmt.Println(string(data))
}

func main(){
    structTest2()
}
json序列化與反序列化

4、錯誤處理

定義錯誤

import "errors"
var errNotFound error = errors.New("not found")

自定義錯誤

error是一個接口類型

type error interface{
    Error() string  
}

實現該接口,自定義錯誤

package main

import (
    "fmt"
    "os"
    "time"
)

type myErr struct{
    Op string
    Path string
    create string
}

func (that *myErr) Error()string{
    return fmt.Sprintf("path:%v, create:%v, op:%v",that.Path, that.create, that.Op)
}

func Open(filename string) error{
    file, err := os.Open(filename)
    if err != nil{
        return &myErr{
            Op: "read",
            Path: filename,
            create: fmt.Sprintf("%v",time.Now()),
        }
    }
    defer file.Close()
    return nil
}

func main(){
    err := Open("c/sadadsad")
    fmt.Println(err)
}
相關文章
相關標籤/搜索