Thursday, December 7, 2023
HomeSoftware EngineeringThe best way to learn a file line by line in Go

The best way to learn a file line by line in Go


If it’s essential to learn a file line by line in Go, then you should use the bufio bundle as follows:

bundle important
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
func important() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Deadly(err)
    }
    defer file.Shut()
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Textual content())
    }
    if err := scanner.Err(); err != nil {
        log.Deadly(err)
    }
}

Simply word that the Scanner will throw an error if any line has a personality depend longer than 65536. This relates again to a 64K measurement restrict. On this case, you should use the Buffer technique to extend the capability.

As illustrated with the maxCapacity variable beneath on line 17:

bundle important
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
func important() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Deadly(err)
    }
    defer file.Shut()
    scanner := bufio.NewScanner(file)

    // -- swap this variable out
    const maxCapacity = longLineLen  // your required line size
    buf := make([]byte, maxCapacity)
    // --

    for scanner.Scan() {
        fmt.Println(scanner.Textual content())
    }
    if err := scanner.Err(); err != nil {
        log.Deadly(err)
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments