How do I read text files in Golang?

Barbara Streisand
Release: 2024-11-27 07:10:13
Original
636 people have browsed it

How do I read text files in Golang?

Reading Text Files in Golang

When working with text files, reading their contents into variables becomes necessary. Golang provides several ways to achieve this, as demonstrated below:

Direct Output

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.

ioutil.ReadAll

This function reads all file contents into memory as bytes:

b, err := io.ReadAll(file)
fmt.Print(b)
Copy after login

io.Reader.Read

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
    }
}
Copy after login

bufio.Scanner

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template