Idiomatic Line Reading in Go
Despite the availability of low-level byte array-returning line reading functions in Go's standard library, an easier and more idiomatic approach exists for obtaining strings from a readline operation.
Solution
To seamlessly read line-by-line from a file, the Readln(*bufio.Reader) function can be employed. It retrieves a line (excluding the linefeed character) from the provided bufio.Reader struct.
Here's a code snippet demonstrating the usage of Readln:
// 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 }
This function can be utilized to read each line from a file:
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) }
This code reads line by line from the specified file and prints each line to standard output.
The above is the detailed content of How to Idiomatically Read Lines from a File in Go?. For more information, please follow other related articles on the PHP Chinese website!