操作终端相关文件句柄常量
os.Stdin:
os.Stdout:
os.Stderr:
终端读写示例:
package main
import "fmt"
type Student struct {
Name string
Age int
Score float32
}
func main() {
var str = "stu01 18 89.22"
var stu Student
fmt.Sscanf(str, "%s %d %f", &stu.Name, &stu.Age, &stu.Score)
fmt.Println(str)
}
fmt.Sscanf 可以从一个字符串里面格式化输入。提取出来后,存入 struct。
带缓冲区的读写:
package main
import (
"bufio"
"fmt"
"os"
)
type Student struct {
Name string
Age int
Score float32
}
func main() {
reader := bufio.NewReader(os.Stdin)
str, err := reader.ReadString('\n')
if err != nil {
fmt.Println("read string failes,err: ", err)
return
}
fmt.Printf("read str succ, ret:%s \n", str)
}
运行结果:
PS F:\go\src> .\main.exe
asdfbaosdifn
read str succ, ret:asdfbaosdifn
PS F:\go\src>
读一个文件,并统计文件各种字符的数量,注意,用到了rune这个转换:
package main
import (
"bufio"
"fmt"
"io"
"os"
)
type charCount struct {
ChCount int
NumCount int
SpaceCount int
Other int
}
func main() {
file, err := os.Open("F:\\go\\src\\go_dev\\day7\\example\\example01\\main\\main.go")
defer file.Close() //记得要关闭文件句柄
if err != nil {
fmt.Println("rad file err :", err)
return
}
var count charCount
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('n')
if err == io.EOF {
break
}
if err != nil {
fmt.Println("rad string failed", err)
break
}
/*
switch {
case err == io.EOF:
break //这样子写的话,会导致死循环,也就是后面的UNreachable code报错
case err != nil:
fmt.Println("rad string failed", 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.Other++
}
}
}
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.Other)
}
运行结果:
PS F:\go\src> go build .\go_dev\day7\example\example02\main\main.go
PS F:\go\src> .\main.exe
char count:256
num count: 9
space count:70
other count:130
PS F:\go\src>