Table of Contents
Whole file reading
Press line Reading
Read word by word
Read the file in chunks
Binary reading
总结
Home Backend Development Golang How to read files in Go language? A brief analysis of various methods

How to read files in Go language? A brief analysis of various methods

Apr 20, 2023 pm 06:28 PM
golang go language

How to read files in Go language? A brief analysis of various methods

This article will discuss how to read files in Golang. We will use the following packages to process these files.

  • os package provides a platform-independent interface to perform operation-level operations.
  • IOutil The package provides easy-to-use utility functions for working with files without knowing much about the internal implementation.
  • bufio package implements buffered IO, which helps us improve the performance and throughput of input and output operations.
  • log package implements a simple logging package. We will use this throughout the program. We will use the Fatal() function of the logging package in our program.

Whole file reading

We can easily read the whole file in one go and store it in a variable. But remember, we shouldn't do this with large files. We will use the ioutil.ReadFile() function to read a file and store the contents of the file in a variable.

First, let's store a file in the same directory as our program. Therefore, our folder structure will look like this.

___ 
| 
|_ _ _ _ ilovego.txt | 
|_ _ _ _ main.go
Copy after login

We write the following in the main.go function:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
)

func main() {

	content, err := ioutil.ReadFile("ilovego.txt")

	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(content))
}
Copy after login

But first, let’s discuss the ReadFile() function Situation:

  • Definition: Method declaration func ReadFile(filename string) ([]byte, error)
  • Function: The read path is passed into the function parameter file and returns the contents of the file. Internally used os.ReadFile(fileName) method
  • Returns: Returns the contents of the file and the error in a byte array. A successful call will return err == nil

The internal ReadFile function is implemented as follows:

func ReadFile(filename string) ([]byte, error) {
    return os.ReadFile(filename)
}
Copy after login

Now, let’s return to our program:

  • ioutil.ReadFile("readthisfile.txt") Returns a byteArray and an err. We store the byteArray in the "content" variable and the error in the "err" variable.
  • Then we put an if condition, if the err value is not nil, we will use the log.Fatal() function to print the error err. Remember, the Fatal() function is equivalent to the Print() function, which then calls os.Exit(1).
  • Finally, we will use the fmt.Println() function to print the contents of the file. We cannot simply print the content variable because it is a byte array and we need to convert it to a string: string(content)
## Then create a new

ilovego.txt file and write the following content:

I Love Golang,
This is One of the Best Languages on the World!
Copy after login

Finally, execute the above code and you can see the following output:

$ go run main.go
I Love Golang, 
This is One of the Best Languages on the World!
Copy after login

Press line Reading

Scanner Scanner provides a convenient interface for reading data, such as a file consisting of newline-delimited lines of text. It reads data through markers; the

Split function defines markers. By default, this function breaks the data into rows and strips the row ends.

package main

import (
	"fmt"
	// "io/ioutil"
	"bufio"
	"log"
	"os"
)

func main() {

	// opening the file using Open function
	f, err := os.Open("ilovego.txt")

	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	// create a scanner for the file
	scanner := bufio.NewScanner(f)

	// loop through the scanner until it return fasle
	for scanner.Scan() {

		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}
}
Copy after login

  • os.Open() Open the file passed in the argument. If any error is encountered while opening the file, it will return the same error. Otherwise, the error will be nil.
  • We then use a scanner to read the file and scan line by line until the end of the file content.
  • Finally, we want to close the file.
Execute the program, the results are as follows:

How to read files in Go language? A brief analysis of various methods

Read word by word

We can also pass Read the file word by word:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	f, err := os.Open("ilovego.txt")

	if err != nil {
		fmt.Println(err)
	}

	defer f.Close()

	scanner := bufio.NewScanner(f)
	scanner.Split(bufio.ScanWords)

	for scanner.Scan() {

		fmt.Println(scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		fmt.Println(err)
	}
}
Copy after login

Run the code:

$ go run main.go
I
Love
Golang,
This
is
One
of
the
Best
Languages
on
the
World!
Copy after login

Read the file in chunks

Read the entire file at once It seems like a simple method, but sometimes we need to make our program some optimizations from a memory management perspective. Golang provides a way to read a file in chunks instead of reading it as a whole or even line by line. Because if the size of a row is too large, reading row by row may also be inefficient.

package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
)

func main() {

	f, err := os.Open("ilovego.txt")

	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	reader := bufio.NewReader(f)
	buf := make([]byte, 16)

	for {
                // reading a file upto buffer
		n, err := reader.Read(buf)

		if err != nil {

			if err != io.EOF {

				log.Fatal(err)
			}

			break
		}

		fmt.Print(string(buf[0:n]))
	}

	fmt.Println()
}
Copy after login

Binary reading

hex package implements hexadecimal encoding and decoding.

package main

import (
	"bufio"
	"encoding/hex"
	"fmt"
	"io"
	"log"
	"os"
)

func main() {

	f, err := os.Open("sid.jpg")

	if err != nil {
		log.Fatal(err)
	}

	defer f.Close()

	reader := bufio.NewReader(f)
	buf := make([]byte, 256)

	for {
		_, err := reader.Read(buf)

		if err != nil {
			if err != io.EOF {
				fmt.Println(err)
			}
			break
		}

		fmt.Printf("%s", hex.Dump(buf))
	}
}
Copy after login

总结

本文介绍了 Go 语言读取文件的几种方式,ioutil.ReadFile 函数将整个文件读成一个字符串。这个函数很方便,但不应该用于非常大的文件。希望能对你有所帮助!

推荐学习:Golang教程

The above is the detailed content of How to read files in Go language? A brief analysis of various methods. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

See all articles