在不將文件內容讀入內存的情況下,如何從文件中讀取“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 方法非常接近我想要的,但它需要一個現有的緩沖區才能工作,而我希望從文件中讀取任意數量的字節而不需要將整個內容讀入內存。完成此任務的最佳方法是什么?
2 回答

HUWWW
TA貢獻1874條經驗 獲得超12個贊
使用此功能:
// 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 */
- 2 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消