Home Backend Development Golang What are some examples of file operations in Go?

What are some examples of file operations in Go?

Jun 09, 2023 pm 11:00 PM
go language File operations Example

As an emerging programming language, Go language is still relatively young compared to other programming languages ​​in terms of file operations, but it already has very powerful and flexible features. This article mainly answers the following questions: What are some examples of file operations in Go language? First, we need to understand that in Go, file operations require the use of the os package and the io package.

1. Reading files

Reading files is the most important type of file operation. Go language provides a variety of ways to complete the operation of reading files, as follows:

  1. Open the file stream through the os.Open() function, and then use the bufio.NewReader() function to wrap the stream. Finally, the file text is read line by line through the bufio.ReadLine() function.
func readFileByLine(filePath string) ([]string, error) {
    file, err := os.Open(filePath)
    if err != nil {
        return nil, err
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    scanner.Split(bufio.ScanLines)

    var lines []string
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }

    return lines, nil
}
Copy after login
  1. Read the file content directly through the ioutil.ReadFile() function in the io/ioutil library, and read all the file content into []byte.
func readFile(filename string) ([]byte, error) {
    return ioutil.ReadFile(filename)
}
Copy after login

2. Writing files

Writing files is also one of the common file operations. You can create a file using the os.OpenFile() function of the os package, and then use io. WriteString() function or bufio.NewWriter() function wraps the file stream for writing. The sample code is as follows:

func writeFile(filename string, content string) error {
    file, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
    if err != nil {
        return err
    }
    defer file.Close()

    writer := bufio.NewWriter(file)
    if _, err := io.WriteString(writer, content); err != nil {
        return err
    }

    return nil
}
Copy after login

3. Copy files

The os package in Go language provides a Copy( ) function, which can easily implement the file copy function. The sample code is as follows:

func copyFile(src, dst string) (int64, error) {
    srcFile, err := os.Open(src)
    if err != nil {
        return 0, err
    }
    defer srcFile.Close()

    dstFile, err := os.Create(dst)
    if err != nil {
        return 0, err
    }
    defer dstFile.Close()

    return io.Copy(dstFile, srcFile)
}
Copy after login

4. Delete files

In Go language, you can use the os.Remove() function to delete files. If we want to delete a folder, we also need to use os.RemoveAll () function. The sample code is as follows:

func deleteFile(filePath string) error {
    return os.Remove(filePath)
}
func deleteDir(dirPath string) error {
    return os.RemoveAll(dirPath)
}
Copy after login

5. Moving files

Using the os.Rename() function of the os package can easily implement file moving operations. The sample code is as follows:

func moveFile(src, dst string) error {
    return os.Rename(src, dst)
}
Copy after login

6. File permission settings

In Go language, you can use the os.Chmod() function to set file permissions. The sample code is as follows:

func chmodFile(filename string, mode os.FileMode) error {
    return os.Chmod(filename, mode)
}
Copy after login

The Go language has rich file operation interfaces. Although the above examples are not comprehensive, they are enough to illustrate the characteristics and flexibility of the Go language in file operations. Even during file operations, we can use file streams, pipes, buffers and other methods to achieve our needs. Through this article, we have also deeply realized the simplicity and ease of use of the Go language.

The above is the detailed content of What are some examples of file operations in Go?. 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
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...

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. �...

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

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 is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

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, ...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles