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
Release: 2024-11-14 14:07:02
Original
1075 people have browsed it

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)
}
Copy after login

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)
Copy after login
  • 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
    }
}
Copy after login
  • 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
}
Copy after login

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!

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