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()
}
输出:
原文地址:https://blog.51cto.com/5660061/2361203