Go: Skip bytes from a stream using io.reader

huangapple go评论82阅读模式
英文:

Go: Skip bytes from a stream using io.reader

问题

在Go语言中,使用io.Reader跳过一定数量的字节的最佳方法是什么?也就是说,标准库中是否有一个函数,它接受一个_reader_和一个_count_,并从_reader_中读取和丢弃_count_个字节?

示例用法:

func DoWithReader(r io.Reader) {      
    SkipNBytes(r, 30);     // 从reader中读取并丢弃30个字节
}

我不需要在流中向后移动,所以最好不要将io.Reader转换为其他类型的读取器。

英文:

What is the best way in Go to skip forward a number of bytes in a stream using io.Reader? That is, is there a function in the standard library which takes a reader and a count that will read and dispose count bytes from the reader?

Example use case:

func DoWithReader(r io.Reader) {      
    SkipNBytes(r, 30);     // Read and dispose 30 bytes from reader
}

I don't need to go backwards in the stream so anything that can work without converting io.Reader to another reader type would be preferred.

答案1

得分: 29

你可以使用以下代码片段:

import "io"

io.CopyN(io.Discard, yourReader, count)

它将请求的字节数复制到一个将读取内容丢弃的io.Writer中。

如果你的io.Reader是一个io.Seeker,你可能想要考虑在流中进行定位,以跳过你想要跳过的字节数:

import "io"

switch r := yourReader.(type) {
case io.Seeker:
    r.Seek(count, io.SeekCurrent)
default:
    io.CopyN(io.Discard, r, count)
}
英文:

You could use this construction:

import "io"

io.CopyN(io.Discard, yourReader, count)

It copies the requested amount of bytes into an io.Writer that discards what it reads.

If your io.Reader is an io.Seeker, you might want to consider seeking in the stream to skip the amount of bytes you want to skip:

import "io"

switch r := yourReader.(type) {
case io.Seeker:
    r.Seek(count, io.SeekCurrent)
default:
    io.CopyN(io.Discard, r, count)
}

huangapple
  • 本文由 发表于 2013年12月2日 11:58:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/20320582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定