Golang, a proper way to rewind file pointer

后端 未结 1 1482
-上瘾入骨i
-上瘾入骨i 2021-02-19 04:46
package main

import (
    \"bufio\"
    \"encoding/csv\"
    \"fmt\"
    \"io\"
    \"log\"
    \"os\"
)

func main() {
    data, err := os.Open(\"cc.csv\")
    defer d         


        
1条回答
  •  醉话见心
    2021-02-19 05:26

    Seeking to the beginning of the file is easiest done using File.Seek(0, 0) (or more safely using a constant: File.Seek(0, io.SeekStart)) just as you suggested, but don't forget that:

    The behavior of Seek on a file opened with O_APPEND is not specified.

    (This does not apply to your example though.)

    Setting the pointer to the beginning of the file is always much faster than closing and reopening the file. If you need to read different, "small" parts of the file many times, alternating, then maybe it might be profitable to open the file twice to avoid repeated seeking (worry about this only if you have peformance problems).

    And again, *os.File implements io.Reader, so you can use it as an io.Reader. I don't know what ioutil.NewReader(data) is you mentioned in your question (package io/ioutil has no such function; maybe you meant bufio.NewReader()?), but certainly it is not needed to read from a file.

    0 讨论(0)
提交回复
热议问题