golang read line by line

huangapple go评论80阅读模式
英文:

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())
	}
}

huangapple
  • 本文由 发表于 2015年6月12日 23:02:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/30806288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定