Golang,一种倒带文件指针的正确方法 [英] Golang, a proper way to rewind file pointer

查看:40
本文介绍了Golang,一种倒带文件指针的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)
        }

    }
}

我在这里使用两个阅读器来读取csv文件.要倒带文件,我使用 data.Seek(0,0)是一个好方法吗?或者最好关闭文件,然后在第二次阅读之前再次打开.

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

* File 用作 io.Reader 是否也正确?或者最好执行 r:= ioutil.NewReader(data)

Is it also correct to use *File as an io.Reader ? Or it's better to do r := ioutil.NewReader(data)

推荐答案

使用 File.Seek(0,0) (或更安全地使用常量: File.Seek(0,io.SeekStart)),就像您建议的那样,但请不要忘记:

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:

未指定使用O_APPEND打开的文件上Seek的行为.

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).

再次, * os.File 实现了 io.Reader ,因此您可以将其用作 io.阅读器.我不知道您在问题中提到了什么 ioutil.NewReader(data)(软件包 bufio.NewReader() ?),但肯定不需要从文件中读取.

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.

这篇关于Golang,一种倒带文件指针的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆