英文:
Get next-to-last line from a file
问题
我找到了一种方法来读取文件中的最后一行,但是我的文件的最后一行是空的,我需要读取倒数第二行,但我不知道如何做,请帮我一下。
func ll(z string) string {
f, err := os.Open(z)
if err != nil {
log.Fatal(err)
}
bf := bufio.NewReader(f)
for {
switch line, err := bf.ReadString('\n'); err {
case nil:
// 有效的行,打印出来。注意,line 包含尾部的 \n。
fmt.Println(line)
case io.EOF:
if line > "" {
// 文件的最后一行缺少 \n,但仍然有效
fmt.Println(line, "in func")
}
return line
default:
log.Fatal(err)
}
}
}
英文:
I found a method how to read last line in file, but last line in my file is empty, I need to read the next-to-last line and I have no idea how to do it, please help a bit.
func ll(z string) string {
f, err := os.Open(z)
if err != nil {
log.Fatal(err)
}
bf := bufio.NewReader(f)
for {
switch line, err := bf.ReadString('\n'); err {
case nil:
// valid line, echo it. note that line contains trailing \n.
fmt.Println(line)
case io.EOF:
if line > "" {
// last line of file missing \n, but still valid
fmt.Println(line, "in func")
}
return line
default:
log.Fatal(err)
}
}
}
答案1
得分: 2
只需在每次迭代时保存当前行,这样当遇到最后一行时,可以返回prev_line
:
func next_to_last(z string) string {
f, err := os.Open(z)
if err != nil {
log.Fatal(err)
}
bf := bufio.NewReader(f)
prev_line := ""
for {
switch line, err := bf.ReadString('\n'); err {
case nil:
// 有效的行,打印它。注意,line 包含尾随的 \n。
fmt.Println(line)
prev_line = line // 将当前行保存为上一行
case io.EOF:
if line > "" {
// 文件的最后一行缺少 \n,但仍然有效
fmt.Println(line, "in func")
}
return prev_line // 返回上一行
default:
log.Fatal(err)
}
}
}
英文:
Just save the current line every iteration, so that when you encounter the last one, you can return prev_line
:
func next_to_last(z string) string {
f, err := os.Open(z)
if err != nil {
log.Fatal(err)
}
bf := bufio.NewReader(f)
prev_line := ""
for {
switch line, err := bf.ReadString('\n'); err {
case nil:
// valid line, echo it. note that line contains trailing \n.
fmt.Println(line)
prev_line = line // Save line as previous
case io.EOF:
if line > "" {
// last line of file missing \n, but still valid
fmt.Println(line, "in func")
}
return prev_line // Return previous line
default:
log.Fatal(err)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论