Home > Backend Development > Golang > How to Idiomatically Read Lines from a File in Go?

How to Idiomatically Read Lines from a File in Go?

Mary-Kate Olsen
Release: 2024-12-13 00:31:09
Original
290 people have browsed it

How to Idiomatically Read Lines from a File in Go?

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
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template