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()
}
输出:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。