In Golang, reading a text file involves opening it using os.Open() and then using the returned *os.File object to perform read operations. However, simply opening the file will not retrieve its contents.
To obtain file contents, you can use io.ReadAll or manually read in chunks.
Using io.ReadAll:
b, err := io.ReadAll(file) fmt.Print(b)
This method reads the entire file into memory, which is suitable for smaller files.
Manual Chunked Reading:
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 } }
In this approach, you define a buffer and read file contents in chunks, which can be more efficient for large files.
The bufio package provides a convenient way to read text files. It offers the bufio.Scanner type that simplifies tokenizing file contents:
scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) }
The Scan() method advances the scanner's token based on a separator (by default, newlines).
The above is the detailed content of How to Read a Text File in Golang?. For more information, please follow other related articles on the PHP Chinese website!