go - 如何使文件阅读器的功能更有效?

标签 go

我正在尝试这段代码:

// GetFooter returns a string which is the Footer of an edi file
func GetFooter(file *os.File) (out string, err error) {
    // TODO can scanner read files backwards?  Seek can get us to the end of file 
    var lines []string
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }
    line1 := lines[len(lines)-2]
    line2 := lines[len(lines)-1]

    return line1 + "\n" + line2, scanner.Err()  
}

我想知道是否有更便宜的方法来获取文件的最后两行?

最佳答案

扫描缓冲区时,您只能将最后两行保留在内存中。

Try it on Go playground.

package main

import (
    "fmt"
    "bufio"
    "bytes"
    "strconv"
)

func main() {
    var buffer bytes.Buffer
    for i := 0; i < 1000; i++ {
        s := strconv.Itoa(i)
        buffer.WriteString(s + "\n")
    }   
    fmt.Println(GetFooter(&buffer))
}

func GetFooter(file *bytes.Buffer) (out string, err error) {
    var line1, line2 string
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line1, line2 = line2, scanner.Text()
    }
    return line1 + "\n" + line2, scanner.Err()  
}

关于go - 如何使文件阅读器的功能更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60343413/

相关文章:

go - 从容器内运行的应用程序使用 Gmail API

go - 在 Go 中解码 URL

Go io阅读器包装器

select - Go Golang select 语句无法接收发送的值

google-app-engine - Golang 卡在 WaitGroup

go - 如何使用 Go 检索网页并将其转换为 UTF-8

postgresql - 如何设计数据库服务类

go - Go中调用特定类型的函数

go - 我想在 golang 中使用劫持,同时在客户端上得到无效响应

c - 如何将复杂的C结构从Go传输到C