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) }
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:
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) }
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 } } }
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()) } }
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!