Friday, February 17, 2023
HomeSoftware EngineeringMethods to learn a file line by line in Go

Methods to learn a file line by line in Go


If you have to learn a file line by line in Go, then you should use the bufio package deal as follows:

package deal primary
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
func primary() {
    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 notice 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 methodology to extend the capability.

As illustrated with the maxCapacity variable under on line 17:

package deal primary
import (
    "bufio"
    "fmt"
    "log"
    "os"
)
func primary() {
    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