gpt4 book ai didi

go - 如何使文件阅读器更有效地运行?

转载 作者:行者123 更新时间:2023-12-01 20:03:05 25 4
gpt4 key购买 nike

我正在尝试以下代码:

// 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com