首页 > 其他 > 详细

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

时间:2019-03-12 11:09:30      阅读:159      评论:0      收藏:0      [点我收藏+]
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(从终端、文件、字符串读取的小例子)

原文:https://blog.51cto.com/5660061/2361204

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!