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:
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!