go 终端读写
操作终端相关文件句柄常量
- os.Stdin:标准输入
- os.Stdout:标准输出
- os.Stderr:标准错误输出
示例:
package main import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) str, err := reader.ReadString(' ') if err != nil { fmt.Println("read string failed, err:", err) return } fmt.Printf("read str succ, ret:%s ", str) }
go文件读写
os.File封装所有文件相关操作,之前的 os.Stdin, os.Stdout, os.Stderr都是 *os.File
- 打开一个文件进行读操作: os.Open(name string) (*File, error)
- 关闭一个文件:File.Close()
示例:
package main import ( "bufio" "fmt" "os" ) func main() { file, err := os.Open("C:/test.log") if err != nil { fmt.Println("read file err:", err) return } defer file.Close() reader := bufio.NewReader(file) str, err := reader.ReadString(' ') if err != nil { fmt.Println("read string failed, err:", err) return } fmt.Printf("read str succ, ret:%s ", 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("C:/test.log") 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(' ') 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 == ' ': count.SpaceCount++ case v >= '0' && v <= '9': count.NumCount++ default: count.OtherCount++ } } } fmt.Printf("char count:%d ", count.ChCount) fmt.Printf("num count:%d ", count.NumCount) fmt.Printf("space count:%d ", count.SpaceCount) fmt.Printf("other count:%d ", count.OtherCount) }
读取压缩文件示例
package main import ( "bufio" "os" "fmt" "compress/gzip" ) func main() { fName := "E:/wangjian/go/project/src/go_dev/day7/example/test.txt.gz" var r *bufio.Reader fi, err := os.Open(fName) defer fi.Close() if err != nil{ fmt.Fprintf(os.Stderr, "%v, Can't open %s: error: %s ", os.Args[0], fName, err) os.Exit(1) } fz, err := gzip.NewReader(fi) if err != err { fmt.Fprintf(os.Stderr, "open gzip failed, err: %s", err) return } r = bufio.NewReader(fz) for { line, err := r.ReadString(' ') 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 :清空
第三个参数:权限控制,与Linux上权限控制一样
- r ——> 004
- w——> 002
- x——> 001
文件写入示例:
package main import ( "os" "fmt" "bufio" ) func main() { outputFile, outputError := os.OpenFile("E:/wangjian/go/project/src/go_dev/day7/example/test.txt", os.O_WRONLY|os.O_CREATE, 0666) if outputError != nil { fmt.Println("An error occurred with file creation") } defer outputFile.Close() outputWriter := bufio.NewWriter(outputFile) outputString := "Hello World! " for i := 0; i < 10; i ++ { outputWriter.WriteString(outputString) } outputWriter.Flush() }
拷贝文件示例:
package main import ( "os" "io" "fmt" ) 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, 0644) if err != nil{ return } defer dst.Close() return io.Copy(dst, src) } func main(){ CopyFile("E:/wangjian/go/project/src/go_dev/day7/example/test2.txt", "E:/wangjian/go/project/src/go_dev/day7/example/test.txt") fmt.Println("Copy Done!") }
ReadLine使用
package main import ( "bufio" "fmt" "io" "os" ) func main() { file, err := os.Open("E:/wangjian/go/project/src/go_dev/day7/example/test.txt") if err != nil { fmt.Println(err) return } defer file.Close() reader := bufio.NewReader(file) var line []byte for { data, prefix, err := reader.ReadLine() if err == io.EOF { break } line = append(line, data...) if !prefix { fmt.Printf("data:%s ", string(line)) line = line[:] } } }
命令行参数
os.Args是一个string的切片,用来存储所有的命令行参数
package main import ( "fmt" "os" ) func main() { fmt.Printf("len of args:%d ", len(os.Args)) for i, v := range os.Args { fmt.Printf("args[%d]=%s ", 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("log level:", logLevel) }