Home > Backend Development > Golang > How to Efficiently Read a Line from a File as a String in Go?

How to Efficiently Read a Line from a File as a String in Go?

Barbara Streisand
Release: 2024-12-08 03:18:11
Original
629 people have browsed it

How to Efficiently Read a Line from a File as a String in Go?

readline to String in Go

In Go, the standard library provides low-level raw functions for readline operations, which return byte arrays. Is there a more convenient method to obtain a string from a readline function?

Idiomatic Solution

The idiomatic approach to readline to string in Go is to utilize the bufio.Reader struct. The Readln() function returns a line (without the trailing newline n) from the input buffered reader.

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

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
}

func main() {
    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 function reads lines from a file, stripping the newline character (n) and printing each line to the console.

The above is the detailed content of How to Efficiently Read a Line from a File as a String 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