When working with text files, reading their contents into variables becomes necessary. Golang provides several ways to achieve this, as demonstrated below:
To print the entire text file's contents, use fmt.Print(file). However, this will output the file descriptor's pointer value, not the file's contents.
This function reads all file contents into memory as bytes:
b, err := io.ReadAll(file) fmt.Print(b)
Reading in smaller chunks can be more memory-efficient for large files:
buf := make([]byte, 32*1024) // Define buffer size 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 } }
Using a Scanner tokenizes the file based on separators, with the default being newlines:
scanner := bufio.NewScanner(file) for scanner.Scan() { fmt.Println(scanner.Text()) // Token as unicode characters fmt.Println(scanner.Bytes()) // Token as bytes }
For additional information and examples, refer to the Golang file cheatsheet for comprehensive file handling techniques.
The above is the detailed content of How do I read text files in Golang?. For more information, please follow other related articles on the PHP Chinese website!