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

查看:20
本文介绍了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)(包 io/ioutil 没有这样的功能;也许你的意思是 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天全站免登陆