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

How to Efficiently Read a Single Line from a Text File into a String in Go?

DDD
Release: 2024-12-20 08:10:14
Original
571 people have browsed it

How to Efficiently Read a Single Line from a Text File into a String in Go?

Reading a String from a Text File in Go

When working with text files in Go, it may be desirable to read a line of text into a string. While the standard library provides low-level functions that return byte arrays, a more convenient way is to use specialized functions that handle this task directly.

Solution

The following code demonstrates how to read a single line from a text file into a string:

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

// ReadLine reads a single line from a file.
func ReadLine(r *bufio.Reader) (string, error) {
    var (
        isPrefix bool = true
        err       error
        line, ln  []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }

    return string(ln), err
}

func main() {
    fi := `<path-to-your-file>`
    f, err := os.Open(fi)
    if err != nil {
        fmt.Println("error opening file= ", err)
        os.Exit(1)
    }
    defer f.Close()

    r := bufio.NewReader(f)
    s, e := ReadLine(r)
    for e == nil {
        fmt.Println(s)
        s, e = ReadLine(r)
    }
}
Copy after login

This code opens the specified file, initializes a buffered reader, and calls the ReadLine function to read each line from the file. The resulting string is printed to stdout.

Usage

Call the ReadLine function on a buffer reader to get the contents of a single line as a string. The ReadLine function handles reading multiple lines if newline characters are not present in the input.

This approach eliminates the need to handle byte arrays and convert them to strings manually, providing a simple and efficient way to read line-oriented text files.

The above is the detailed content of How to Efficiently Read a Single Line from a Text File into 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template