Home >Backend Development >Golang >How to read the contents of a text file into a variable in Golang?

How to read the contents of a text file into a variable in Golang?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-14 14:07:021074browse

How to read the contents of a text file into a variable in Golang?

Reading a Text File in Golang

How can I read the contents of "file.txt" into a variable in Golang?

package main

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

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

    fmt.Print(file)
}

Answer:

The provided code successfully reads the file, but it prints the pointer value of the file descriptor rather than the file content. To obtain the file content, you need to read from the file descriptor.

Options for Reading File Content:

  • ReadAll: Reads all file content into memory as bytes.
b, err := io.ReadAll(file)
fmt.Print(b)
  • Read in Chunks: Reads the file content in smaller chunks to avoid memory issues with large files.
buf := make([]byte, 32*1024) // Define your buffer size.

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

    if n > 0 {
        fmt.Print(buf[:n]) // Your read buffer.
    }

    if err == io.EOF {
        break
    }
    if err != nil {
        log.Printf("read %d bytes: %v", n, err)
        break
    }
}
  • bufio Scanner: Advances the token by newline by default.
scanner := bufio.NewScanner(file)

for scanner.Scan() {
    fmt.Println(scanner.Text()) // Token in unicode-char
    fmt.Println(scanner.Bytes()) // Token in bytes
}

Additional Resources:

  • [go-lang file cheatsheet](https://go-lang-file-utils.readthedocs.io/)

The above is the detailed content of How to read the contents of a text file into a variable in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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