英文:
golang read line by line
问题
我开始学习一点Go语言,但是我完全无法理解如何按照传统的方式逐行读取:
while filehandler != EOF {
line_buffer = readline(filehandler)
}
我知道我需要使用bufio的scanlines。这不是我正在使用的代码,我只是试图解释这个想法。
英文:
I've started studying golang a bit and I'm absolutely unable to understand how I'm supposed to read line by line in the old-fashioned way:
while filehandler != EOF {
line_buffer = readline(filehandler)
}
I'm aware that I have to use bufio scanlines. This isn't what I am using as code, I'm merely trying to explain the idea.
答案1
得分: 9
使用这个:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, _ := os.Open("path/to_file")
fscanner := bufio.NewScanner(file)
for fscanner.Scan() {
fmt.Println(fscanner.Text())
}
}
使用这段代码可以打开一个文件并逐行读取文件内容。
英文:
use this:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
file, _ := os.Open("path/to_file")
fscanner := bufio.NewScanner(file)
for fscanner.Scan() {
fmt.Println(fscanner.Text())
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论