package main
import (
"fmt"
"io"
"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 sampleReadFile() {
file, _ := os.Open("io.go")
defer file.Close()
// 从文件读取9个字节
data, _ := ReadFrom(file, 9)
// fmt.Println(data)
fmt.Println(string(data))
}
func main() {
sampleReadFile()
}
// 输出
MacintoshdeMacBook-Pro-139:io elasticnotes$ go run io2.go
please input stdin:
// [112 97 99 107 97 103 101 32 109]
package m