Home >Backend Development >Golang >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:
b, err := io.ReadAll(file) fmt.Print(b)
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 } }
scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) // Token in unicode-char fmt.Println(scanner.Bytes()) // Token in bytes }
Additional Resources:
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!