Go readline & # 8594; string

What is the idiomatic way to make readline for a line in Go? the raw functions provided in the standard library seem really low, they return byte arrays. Is there a built-in easier way to get a string from the readline function?

+8
go
May 26 '11 at 16:07
source share
2 answers

I wrote a way to easily read each line from a file. The Readln function (* bufio.Reader) returns a string (sans \ n) from the base structure of bufio.Reader.

// 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 each line from a file. The following code reads each line in the file and prints each line to standard output.

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

Hurrah!

+11
Aug 30 '12 at 22:17
source share

Here 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) } 
+10
May 26 '11 at 18:46
source share



All Articles