终端读写
1. 终端读写
操作终端相关文件句柄常量
- os.Stdin:标准输入
- os.Stdout:标准输出
- os.Stderr:标准错误输出
2. 终端读写示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 1package main
2
3import (
4 "fmt"
5)
6
7var (
8 firstName, lastName, s string
9 i int
10 f float32
11 input = "56.12 / 5212 / Go"
12 format = "%f / %d / %s"
13)
14
15func main() {
16 fmt.Println("Please enter your full name: ")
17 fmt.Scanln(&firstName, &lastName)
18 // fmt.Scanf("%s %s", &firstName, &lastName)
19 fmt.Printf("Hi %s %s!\n", firstName, lastName) // Hi Chris Naegels
20 fmt.Sscanf(input, format, &f, &i, &s)
21 fmt.Println("From the string we read: ", f, i, s)
22}
23 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 1package main
2
3import "fmt"
4
5type student struct {
6 Name string
7 Age int
8 Score float32
9}
10
11func main() {
12 var str = "stu01 18 89.92"
13 var stu student
14 fmt.Sscanf(str, "%s %d %f", &stu.Name, &stu.Age, &stu.Score)
15 fmt.Println(stu)
16}
17 |
终端读写示例
3. 带缓冲区的读写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 1package main
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7)
8
9var inputReader *bufio.Reader
10var input string
11var err error
12
13func main() {
14 inputReader = bufio.NewReader(os.Stdin)
15 fmt.Println("Please enter some input: ")
16 input, err = inputReader.ReadString('\n')
17 if err == nil {
18 fmt.Printf("The input was: %s\n", input)
19 }
20}
21 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 1package main
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7)
8
9func main() {
10 reader := bufio.NewReader(os.Stdin)
11 str, err := reader.ReadString('\n')
12 if err != nil {
13 fmt.Println("read string failed, err:", err)
14 return
15 }
16
17 fmt.Printf("read str success, ret: %s\n", str)
18}
19
20// go run go_dev/day7/example/example3/main
21 |
带缓冲区的读写
文件读写
1. os.File封装所有文件相关操作,之前讲的 os.Stdin,os.Stdout, os.Stderr都是*os.File
- 打开一个文件进行读操作: os.Open(name string) (*File, error)
- 关闭一个文件:File.Close()
-
文件操作示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| 1package main
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7)
8
9func file_write() {
10 // 文件读写
11 file, err := os.OpenFile("test.log", os.O_CREATE|os.O_WRONLY, 0664)
12 if err != nil {
13 fmt.Println("open file err,:", err)
14 return
15 }
16 fmt.Fprintf(file, "do balance error\n")
17 file.Close()
18}
19
20func main() {
21 // file_write()
22 file, err := os.Open("test.log")
23 if err != nil {
24 fmt.Println("read file failed, err:", err)
25 return
26 }
27
28 defer file.Close()
29
30 reader := bufio.NewReader(file)
31 str, err := reader.ReadString('\n')
32 if err != nil {
33 fmt.Println("read string failed, err:", err)
34 return
35 }
36
37 fmt.Printf("read str success, ret: %s\n", str)
38}
39 |
-
读取整个文件示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 1package main
2
3import (
4 "fmt"
5 "io/ioutil"
6 "os"
7)
8
9func main() {
10
11 inputFile := "products.txt"
12 outputFile := "products_copy.txt"
13 buf, err := ioutil.ReadFile(inputFile)
14 if err != nil {
15 fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
16 return
17 }
18
19 fmt.Printf("%s\n", string(buf))
20 err = ioutil.WriteFile(outputFile, buf, 0x644)
21 if err != nil {
22 panic(err.Error())
23 }
24}
25 |
-
读取压缩文件示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| 1package main
2
3import (
4 "bufio"
5 "compress/gzip"
6 "fmt"
7 "os"
8)
9func main() {
10 fName := "MyFile.gz"
11 var r *bufio.Reader
12 fi, err := os.Open(fName)
13 if err != nil {
14 fmt.Fprintf(os.Stderr, "%v, Can’t open %s: error: %s\n", os.Args[0], fName, err)
15 os.Exit(1)
16 }
17 fz, err := gzip.NewReader(fi)
18 if err != nil {
19 fmt.Fprintf(os.Stderr, "open gzip failed, err: %v\n", err)
20 return
21 }
22 r = bufio.NewReader(fz)
23 for {
24 line, err := r.ReadString('\n')
25 if err != nil {
26 fmt.Println("Done reading file")
27 os.Exit(0)
28 }
29 fmt.Println(line)
30 }
31}
32 |
5. 文件写入
1 2
| 1os.OpenFile(“output.dat”, os.O_WRONLY|os.O_CREATE, 0666)
2 |
第二个参数:文件打开模式
-
- os.O_WRONLY:只写
-
- os.O_CREATE:创建文件
-
- os.O_RDONLY:只读
-
- os.O_RDWR:读写
-
- os.O_TRUNC :清空
第三个参数:权限控制:
r –> 004w –> 002x –> 001
6.文件写入示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| 1package main
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7)
8
9func main() {
10 outputFile, outputError := os.OpenFile("output.dat",
11os.O_WRONLY|os.O_CREATE, 0666)
12 if outputError != nil {
13 fmt.Printf("An error occurred with file creation\n")
14 return
15 }
16
17 defer outputFile.Close()
18 outputWriter := bufio.NewWriter(outputFile)
19 outputString := "hello world!\n"
20 for i := 0; i < 10; i++ {
21 outputWriter.WriteString(outputString)
22 }
23 outputWriter.Flush()
24}
25 |
7. 拷贝文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| 1package main
2
3import (
4 "fmt"
5 "io"
6 "os"
7)
8
9func main() {
10
11 CopyFile("target.txt", "source.txt")
12 fmt.Println("Copy done!")
13}
14
15func CopyFile(dstName, srcName string) (written int64, err error) {
16 src, err := os.Open(srcName)
17 if err != nil {
18 return
19 }
20 defer src.Close()
21 dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
22 if err != nil {
23 return
24 }
25 defer dst.Close()
26 return io.Copy(dst, src)
27}
28 |
8 读取文件,统计英文、数字、空格以及其他字符的数量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| 1package main
2
3import (
4 "bufio"
5 "fmt"
6 "io"
7 "os"
8)
9
10type CharCount struct {
11 ChCount int
12 NumCount int
13 SpaceCount int
14 OtherCount int
15}
16
17func main() {
18 file, err := os.Open("test.log")
19 if err != nil {
20 fmt.Println("read file failed, err:", err)
21 return
22 }
23
24 defer file.Close()
25
26 var count CharCount
27
28 reader := bufio.NewReader(file)
29 for {
30 str, err := reader.ReadString('\n')
31 if err == io.EOF {
32 break
33 }
34 if err != nil {
35 fmt.Printf("read file failed, err%s", err)
36 break
37 }
38 runeArr := []rune(str)
39 for _, v := range runeArr {
40 switch {
41 case v >= 'a' && v <= 'z':
42 fallthrough
43 case v >= 'A' && v <= 'Z':
44 count.ChCount++
45 case v == ' ' || v == '\t':
46 count.SpaceCount++
47 case v >= '0' && v <= '9':
48 count.NumCount++
49 default:
50 count.OtherCount++
51 }
52 }
53 }
54 fmt.Printf("char count: %d\n", count.ChCount)
55 fmt.Printf("num count: %d\n", count.NumCount)
56 fmt.Printf("space count: %d\n", count.SpaceCount)
57 fmt.Printf("other count: %d\n", count.OtherCount)
58}
59 |
9. 带缓冲区的文件读写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| 1package main
2
3import (
4 "bufio"
5 "flag"
6 "fmt"
7 "io"
8 "os"
9)
10
11func cat(r *bufio.Reader) {
12 for {
13 buf, err := r.ReadBytes('\n')
14 if err == io.EOF {
15 break
16 }
17 fmt.Fprintf(os.Stdout, "%s", buf)
18
19 return
20 }
21}
22
23func main() {
24 flag.Parse()
25 if flag.NArg() == 0 {
26 cat(bufio.NewReader(os.Stdin))
27 }
28 for i := 0; i < flag.NArg(); i++ {
29 f, err := os.Open(flag.Arg(i))
30 if err != nil {
31 fmt.Fprintf(os.Stderr, "%s:error reading from %s: %s\n",
32 os.Args[0], flag.Arg(i), err.Error())
33 }
34 continue
35 }
36 cat(bufio.NewReader(f))
37}
38 |
10. 带缓冲区的终端读写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 1package main
2
3import (
4 "bufio"
5 "fmt"
6 "os"
7)
8
9func main() {
10 fmt.Fprintf(os.Stdout, "%s\n", "hello world! - unbuffered")
11 buf := bufio.NewWriter(os.Stdout)
12 fmt.Fprintf(buf, "%s\n", "hello world! - buffered")
13 buf.Flush()
14}
15 |
命令行参数
os.Args是一个string的切片,用来存储所有的命令行参数
1. flag包的使用,用来解析命令行参数:
- flag.BoolVar(&test, "b", false, "print on newline")
- flag.StringVar(&str, "s", "", "print on newline")
- flag.IntVar(&count, "c", 1001, "print on newline")
2. 命令行参数解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 1package main
2
3import (
4 "flag" // command line option parser
5 "fmt"
6)
7
8func main() {
9
10 var test bool
11 var str string
12 var count int
13 flag.BoolVar(&test, "b", false, "print on newline")
14 flag.StringVar(&str, "s", "", "print on newline")
15 flag.IntVar(&count, "c", 1001, "print on newline")
16 flag.Parse()
17
18 fmt.Println(test)
19 fmt.Println(str)
20 fmt.Println(count)
21}
22 |
3. 示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 1package main
2
3import (
4 "fmt"
5 "os"
6)
7
8func main() {
9 fmt.Printf("len of args:%d\n", len(os.Args))
10 for i, v := range os.Args {
11 fmt.Printf("args[%d]: %s\n", i, v)
12 }
13}
14 |
示例一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 1package main
2
3import (
4 "flag"
5 "fmt"
6)
7
8func main() {
9 var confPath string
10 var logLevel int
11 flag.StringVar(&confPath, "c", "", "please input conf Path")
12 flag.IntVar(&logLevel, "d", 10, "please input log level")
13
14 flag.Parse()
15
16 fmt.Println("path:", confPath)
17 fmt.Println("log level:", logLevel)
18}
19
20// go run go_dev/day7/example/example7/main -c d:/python -d 1
21 |
示例二
Json数据协议
-
- 导入包:Import “encoding/json”
-
- 序列化: json.Marshal(data interface{})
-
- 反序列化: json.UnMarshal(data []byte, v interface{})
json序列化结构体,map,slice和int
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| 1package main
2
3import (
4 "encoding/json"
5 "fmt"
6)
7
8type User struct {
9 UserName string `json:"username"`
10 Nickname string `json:"nickname"`
11 Age int
12 Birthday string
13 Sex string
14 Email string
15 Phone string
16}
17
18func testStruct() {
19 user1 := &User{
20 UserName: "user1",
21 Nickname: "超级英雄",
22 Age: 18,
23 Birthday: "2008/8/8",
24 Sex: "男",
25 Email: "mayun@qq.com",
26 Phone: "110",
27 }
28 data, err := json.Marshal(user1)
29 if err != nil {
30 fmt.Println("json.marsha1 failed, err:", err)
31 return
32 }
33 fmt.Printf("%s\n", string(data))
34}
35
36func testInt() {
37 var age = 100
38 data, err := json.Marshal(age)
39 if err != nil {
40 fmt.Println("json.marsha1 failed, err:", err)
41 return
42 }
43 fmt.Printf("%s\n", string(data))
44}
45
46func testMap() {
47 var m map[string]interface{}
48 m = make(map[string]interface{})
49 m["username"] = "user1"
50 m["age"] = 18
51 m["sex"] = "女"
52 data, err := json.Marshal(m)
53 if err != nil {
54 fmt.Println("json.marsha1 failed, err:", err)
55 return
56 }
57 fmt.Printf("%s\n", string(data))
58}
59func testSlice() {
60 var m map[string]interface{}
61 var s []map[string]interface{}
62 m = make(map[string]interface{})
63 m["username"] = "user1"
64 m["age"] = 18
65 m["sex"] = "女"
66
67 s = append(s, m)
68
69 data, err := json.Marshal(s)
70 if err != nil {
71 fmt.Println("json.marsha1 failed, err:", err)
72 return
73 }
74 fmt.Printf("%s\n", string(data))
75}
76func main() {
77 testStruct()
78 testInt()
79 testMap()
80 testSlice()
81}
82 |
json序列化示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| 1package main
2
3import (
4 "encoding/json"
5 "fmt"
6)
7
8type User struct {
9 UserName string `json:"username"`
10 Nickname string `json:"nickname"`
11 Age int
12 Birthday string
13 Sex string
14 Email string
15 Phone string
16}
17
18func testStruct() (ret string, err error) {
19 user1 := &User{
20 UserName: "user1",
21 Nickname: "超级英雄",
22 Age: 18,
23 Birthday: "2008/8/8",
24 Sex: "男",
25 Email: "mayun@qq.com",
26 Phone: "110",
27 }
28 data, err := json.Marshal(user1)
29 if err != nil {
30 fmt.Println("json.marsha1 failed, err:", err)
31 return
32 }
33 ret = string(data)
34 return
35}
36func testMap() (ret string, err error) {
37 var m map[string]interface{}
38 m = make(map[string]interface{})
39 m["username"] = "user1"
40 m["age"] = 18
41 m["sex"] = "女"
42 data, err := json.Marshal(m)
43 if err != nil {
44 fmt.Println("json.marsha1 failed, err:", err)
45 return
46 }
47 ret = string(data)
48 return
49}
50func test() {
51 data, err := testStruct()
52 if err != nil {
53 fmt.Println("test struct failed, err:", err)
54 return
55 }
56 var user1 User
57 err = json.Unmarshal([]byte(data), &user1)
58 if err != nil {
59 fmt.Println("unmarshal failed", err)
60 return
61 }
62 fmt.Println(user1)
63}
64
65func test2() {
66 data, err := testMap()
67 if err != nil {
68 fmt.Println("test map failed, err:", err)
69 return
70 }
71 var m map[string]interface{}
72 err = json.Unmarshal([]byte(data), &m)
73 if err != nil {
74 fmt.Println("unmarshal failed", err)
75 return
76 }
77 fmt.Println(m)
78}
79func main() {
80 test()
81 test2()
82}
83 |
json序列化示例
定义错误
1 2 3 4 5 6 7 8 9 10 11 12 13
| 1package main
2
3import (
4 "errors"
5 "fmt"
6)
7
8var errNotFound error = errors.New("Not found error")
9
10func main() {
11 fmt.Printf("error: %v", errNotFound)
12}
13 |
自定义错误
1 2 3 4
| 1type error interface {
2 Error() string
3}
4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 1package main
2import (
3// "fmt"
4)
5type PathError struct {
6 Op string
7 Path string
8 err string
9}
10func (e *PathError) Error() string {
11 return e.Op + " " + e.Path + ": " + e.Err.Error()
12}
13func test() error {
14 return &PathError{
15 Op: "op",
16 Path: "path",
17 }
18}
19func main() {
20 test()
21}
22 |
判断自定义错误
1 2 3 4 5 6 7 8
| 1switch err := err.(type) {
2case ParseError:
3 PrintParseError(err)
4case PathError:
5 PrintPathError(err)
6... default:
7}
8 |
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| 1package main
2
3import (
4 "fmt"
5 "os"
6 "time"
7)
8
9type PathError struct {
10 path string
11 op string
12 createTime string
13 message string
14}
15
16func (p *PathError) Error() string {
17 return fmt.Sprintf("path=%s op=%s createTime=%s message=%s", p.path, p.op, p.createTime, p.message)
18}
19
20func Open(filename string) error {
21 file, err := os.Open(filename)
22 if err != nil {
23 return &PathError{
24 path: filename,
25 op: "read",
26 message: err.Error(),
27 createTime: fmt.Sprintf("%v", time.Now()),
28 }
29 }
30 defer file.Close()
31 return nil
32}
33
34func main() {
35 err := Open("c:/sasassas.txt")
36 switch v := err.(type) {
37 case *PathError:
38 fmt.Println("get path error,", v)
39 default:
40
41 }
42}
43 |
自定义错误
Panic&Recove
panic的作用就是抛出一条错误信息,从它的参数类型可以看到它可以抛出任意类型的错误信息。在函数执行过程中的某处调用了panic,则立即抛出一个错误信息,同时函数的正常执行流程终止,但是该函数中panic之前定义的defer语句将被依次执行。之后该goroutine立即停止执行。
recover()用于将panic的信息捕捉。recover必须定义在panic之前的defer语句中。在这种情况下,当panic被触发时,该goroutine不会简单的终止,而是会执行在它之前定义的defer语句。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| 1package main
2
3import (
4 "fmt"
5)
6
7func badCall() {
8 panic("bad end")
9}
10
11func test() {
12 defer func() {
13 if e := recover(); e != nil {
14 fmt.Printf("Panicking %s\r\n", e)
15 }
16 }()
17 badCall()
18 fmt.Printf("After bad call\r\n")
19}
20
21func main() {
22 fmt.Printf("Calling test\r\n")
23 test()
24 fmt.Printf("Test completed\r\n")
25}
26 |