如何直接从 Go 中的文件读取任意数量的数据?

在不将文件内容读入内存的情况下,如何从文件中读取“x”字节,以便为每个单独的读取操作指定 x 是什么?


我看到Read各种Readers 的方法采用一定长度的字节片,我可以从文件中读取到该片中。但在那种情况下,切片的大小是固定的,而理想情况下我想做的是:


func main() {

    f, err := os.Open("./file.txt")

    if err != nil {

        panic(err)

    }


    someBytes := f.Read(2)

    someMoreBytes := f.Read(4)

}

bytes.Buffer有一个Next 方法非常接近我想要的,但它需要一个现有的缓冲区才能工作,而我希望从文件中读取任意数量的字节而不需要将整个内容读入内存。


完成此任务的最佳方法是什么?


米脂
浏览 120回答 2
2回答

HUWWW

使用此功能:// readN reads and returns n bytes from the reader.// On error, readN returns the partial bytes read and// a non-nil error.func readN(r io.Reader, n int) ([]byte, error) {    // Allocate buffer for result    b := make([]byte, n)    // ReadFull ensures buffer is filled or error is returned.    n, err := io.ReadFull(r, b)     return b[:n], err}像这样调用:someBytes, err := readN(f, 2)if err != nil  { /* handle error here */someMoreBytes := readN(f, 4)if err != nil  { /* handle error here */

jeck猫

你可以这样做:f, err := os.Open("/tmp/dat")check(err)b1 := make([]byte, 5)n1, err := f.Read(b1)check(err)fmt.Printf("%d bytes: %s\n", n1, string(b1[:n1]))如需更多阅读,请查看网站。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go