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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ioos(从终端文件字符串读取的小例子)相关的知识,希望对你有一定的参考价值。

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()
}

输出:
技术图片

以上是关于ioos(从终端文件字符串读取的小例子)的主要内容,如果未能解决你的问题,请参考以下文章