Golang, the correct way to rewind a file pointer

package main import ( "bufio" "encoding/csv" "fmt" "io" "log" "os" ) func main() { data, err := os.Open("cc.csv") defer data.Close() if err != nil { log.Fatal(err) } s := bufio.NewScanner(data) for s.Scan() { fmt.Println(s.Text()) if err := s.Err(); err != nil { panic(err) } } // Is it a proper way? data.Seek(0, 0) r := csv.NewReader(data) for { if record, err := r.Read(); err == io.EOF { break } else if err != nil { log.Fatal(err) } else { fmt.Println(record) } } } 

I am using two readers here to read from a csv file. To rewind the file, I use data.Seek(0, 0) , is this a good way? Or it’s better to close the file and open it before the second reading.

Is it right to use *File as io.Reader ? Or better to do r := ioutil.NewReader(data)

+9
source share
1 answer

The search at the beginning of the file is easiest to do with File.Seek(0, 0) (or more safely with the constant: File.Seek(0, io.SeekStart) ), as you suggested, but do not forget that:

Seek behavior for a file opened with O_APPEND is not specified.

(This does not apply to your example.)

Setting a pointer to the beginning of a file is always much faster than closing and reopening a file. If you need to alternate between different “small” parts of a file multiple times, then it may be useful to open the file twice to avoid searching again (worry about this only if you have performance problems).

And again, *os.File implements io.Reader , so you can use it as io.Reader . I don’t know what ioutil.NewReader(data) you mentioned in your question (the io/ioutil does not have such a function; perhaps you meant bufio.NewReader() ?), But, of course, you do not need to read it from the file .,

+12
source

Source: https://habr.com/ru/post/1264233/


All Articles