Home > Backend Development > Golang > How to Read the Contents of a Text File in Go?

How to Read the Contents of a Text File in Go?

Barbara Streisand
Release: 2024-11-13 15:13:02
Original
492 people have browsed it

How to Read the Contents of a Text File in Go?

How to Read a Text File in Go

When working with text files in Go, it's essential to understand how to read their contents. However, the question you posed, "How to read a text file? [duplicate]," suggests that this task may be more complex than it seems.

The code you provided:

package main

import (
    "fmt"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Print(file)
}
Copy after login

successfully reads the file, but the output is merely the pointer value of the file descriptor (*os.File). To actually obtain the file's contents, you need to employ one of several techniques:

Reading File Content into Memory

For small files, the simplest approach is to use io/ioutil.ReadAll to load the entire file into memory.

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    b, err := io.ReadAll(file)
    fmt.Print(b)
}
Copy after login

Reading in Chunks

For larger files, reading in chunks can be more memory-efficient.

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    buf := make([]byte, 32*1024)

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n])
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }
}
Copy after login

Using a Scanner

Finally, you can use the bufio package to create a Scanner that reads the file in tokens, advancing based on a separator (by default, newline).

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {
        fmt.Println(scanner.Text())
        fmt.Println(scanner.Bytes())
    }
}
Copy after login

The above is the detailed content of How to Read the Contents of a Text 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