当前位置 : 主页 > 手机开发 > ROM >

io、os(从终端、文件、字符串读取的小例子)

来源:互联网 收集:自由互联 发布时间:2021-06-10
package main import ( "io" "strings" "fmt" "os" ) func ReadFrom(reader io.Reader, num int) ([]byte, error) { p := make([]byte, num) n,err := reader.Read(p) if n 0 { return p[:n], nil } return p, err } //从字符串读 func sampleReadFromSt
package main import ( "io" "strings" "fmt" "os" ) func ReadFrom(reader io.Reader, num int) ([]byte, error) { p := make([]byte, num) n,err := reader.Read(p) if n > 0 { return p[:n], nil } return p, err } //从字符串读 func sampleReadFromString() { data, _ := ReadFrom(strings.NewReader("from string"), 12) fmt.Println(string(data)) } //从终端读 func sampleReadFromStdin() { fmt.Println("please input from std:") data, _ := ReadFrom(os.Stdin, 11) fmt.Println(string(data)) } //从文件读 func sampleReadFromFile() { file, _ := os.Open("io操作.go") defer file.Close() data, _ := ReadFrom(file, 9) fmt.Println(string(data)) } func main() { sampleReadFromString() sampleReadFromStdin() sampleReadFromFile() }

输出:
io、os(从终端、文件、字符串读取的小例子)

网友评论