Home >Backend Development >Golang >How do I read text files in Golang?

How do I read text files in Golang?

Barbara Streisand
Barbara StreisandOriginal
2024-11-27 07:10:13721browse

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)

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
    }
}

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
}

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!

Statement:
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
Previous article:Mastering ENUMs in GoNext article:Mastering ENUMs in Go