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?
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!
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With