go readline -> string

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

go readline -> string

问题

在Go语言中,如何以惯用方式将读取行转换为字符串?标准库提供的原始函数似乎非常底层,它们返回字节数组。是否有任何内置的更简单的方法来从读取行函数中获取字符串?

英文:

What is the idiomatic way to do a readline to string in Go? the raw functions provided in the standard library seem really low level, they return byte arrays. Is there any built in easier way to get a string out of a readline function?

答案1

得分: 15

我写了一个简单的方法来从文件中逐行读取内容。Readln(*bufio.Reader) 函数从底层的 bufio.Reader 结构中返回一行(不包含 \n)。

// Readln 从输入的缓冲读取器中返回一行(不包含结尾的 \n)
// 如果缓冲读取器有错误,将返回错误。
func Readln(r *bufio.Reader) (string, error) {
  var (
    isPrefix bool = true
    err error = nil
    line, ln []byte
  )
  for isPrefix && err == nil {
    line, isPrefix, err = r.ReadLine()
    ln = append(ln, line...)
  }
  return string(ln), err
}

你可以使用 Readln 来读取文件的每一行。以下代码从文件中读取每一行,并将每一行输出到标准输出。

f, err := os.Open(fi)
if err != nil {
    fmt.Println("打开文件错误:", err)
    os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    fmt.Println(s)
    s, e = Readln(r)
}

祝好!

英文:

I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.

// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
  var (isPrefix bool = true
       err error = nil
       line, ln []byte
      )
  for isPrefix && err == nil {
      line, isPrefix, err = r.ReadLine()
      ln = append(ln, line...)
  }
  return string(ln),err
}

You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.

f, err := os.Open(fi)
if err != nil {
    fmt.Println("error opening file= ",err)
    os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    fmt.Println(s)
    s,e = Readln(r)
}

Cheers!

答案2

得分: 14

这里有一些使用bufio.ReadLinebufio.ReadString的示例。

 package main

import (
	"bufio"
	"fmt"
	"os"
)

func ReadLine(filename string) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	r := bufio.NewReaderSize(f, 4*1024)
	line, isPrefix, err := r.ReadLine()
	for err == nil && !isPrefix {
		s := string(line)
		fmt.Println(s)
		line, isPrefix, err = r.ReadLine()
	}
	if isPrefix {
		fmt.Println("buffer size to small")
		return
	}
	if err != io.EOF {
		fmt.Println(err)
		return
	}
}

func ReadString(filename string) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	r := bufio.NewReader(f)
	line, err := r.ReadString('\n')
	for err == nil {
		fmt.Print(line)
		line, err = r.ReadString('\n')
	}
	if err != io.EOF {
		fmt.Println(err)
		return
	}
}

func main() {
	filename := `testfile`
	ReadLine(filename)
	ReadString(filename)
}
英文:

Here's are some examples using bufio.ReadLine and bufio.ReadString.

 package main

import (
	"bufio"
	"fmt"
	"os"
)

func ReadLine(filename string) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	r := bufio.NewReaderSize(f, 4*1024)
	line, isPrefix, err := r.ReadLine()
	for err == nil && !isPrefix {
		s := string(line)
		fmt.Println(s)
		line, isPrefix, err = r.ReadLine()
	}
	if isPrefix {
		fmt.Println("buffer size to small")
		return
	}
	if err != io.EOF {
		fmt.Println(err)
		return
	}
}

func ReadString(filename string) {
	f, err := os.Open(filename)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()
	r := bufio.NewReader(f)
	line, err := r.ReadString('\n')
	for err == nil {
		fmt.Print(line)
		line, err = r.ReadString('\n')
	}
	if err != io.EOF {
		fmt.Println(err)
		return
	}
}

func main() {
	filename := `testfile`
	ReadLine(filename)
	ReadString(filename)
}

答案3

得分: 0

你也可以使用bufio.NewScanner

package main

import (
   "bufio"
   "os"
)

func main() {
   f, e := os.Open("file.txt")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   s := bufio.NewScanner(f)
   for s.Scan() {
      println(s.Text())
   }
}

https://pkg.go.dev/bufio#Scanner

英文:

You can also use bufio.NewScanner:

package main

import (
   "bufio"
   "os"
)

func main() {
   f, e := os.Open("file.txt")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   s := bufio.NewScanner(f)
   for s.Scan() {
      println(s.Text())
   }
}

https://pkg.go.dev/bufio#Scanner

huangapple
  • 本文由 发表于 2011年5月27日 00:07:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/6141604.html
匿名

发表评论

匿名网友

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

确定