SoFunction
Updated on 2025-03-06

A complete guide to reading and writing methods for Golang file operations

Preface

In daily development, reading and writing files are very common operations. This article will introduce in detail how to read and write files in Go language, including file creation, opening, reading, writing, closing and other operations, and explain common error handling and performance optimization methods.

1. Basics of file operation

In Go,osPackage is the main tool for file operations, often withbufioandioPackage for use:

  • os package: Used for basic operations such as creating, opening, writing, and deleting files.
  • bufio package: Supports buffer reading and writing to improve read and write performance.
  • io package: Provides a general I/O operation interface, such asReadandWrite

2. Opening and creating files

2.1 Open the file

()Used toRead-only modeOpen the file. If the file does not exist, an error will be returned.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := ("")
    if err != nil {
        ("Failed to open the file:", err)
        return
    }
    defer () // Delay shutdown to ensure resource release    ("File opens successfully")
}

2.2 Create a file

()A new file will be created, if the file already existsClearFile content.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := ("")
    if err != nil {
        ("File creation failed:", err)
        return
    }
    defer ()
    ("File creation successfully")
}

3. File writing operation

3.1 UseWrite string

We can callWriteStringMethod to write content to the file:

file, err := ("")
if err != nil {
    ("File creation failed:", err)
    return
}
defer ()

_, err = ("Hello, Golang!\n")
if err != nil {
    ("Write failed:", err)
} else {
    ("Content writing successfully")
}

3.2 Buffered write using bufio

Buffer writes reduce the number of disk I/O times and improve write speed.

package main

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

func main() {
    file, err := ("")
    if err != nil {
        ("File creation failed:", err)
        return
    }
    defer ()

    writer := (file)
    _, err = ("This is an example of buffer writes\n")
    if err != nil {
        ("Write failed:", err)
        return
    }
    () // Refresh the buffer to ensure that the content is written to the file    ("Buffered content is successfully written")
}

4. File reading operation

4.1 Read files by line

Used to read files by line, perfect for handling text content:

file, err := ("")
if err != nil {
    ("Failed to open the file:", err)
    return
}
defer ()

scanner := (file)
for () {
    (())
}

if err := (); err != nil {
    ("An error occurred while reading the file:", err)
}

4.2 Read the entire file at once

Can be usedRead the contents of the entire file:

data, err := ("")
if err != nil {
    ("Read failed:", err)
    return
}
("File content:\n", string(data))

5. Detailed explanation of file permissions and opening mode

5.1 Use Set File Open Mode

Allows us to specify the way and permissions to open the file. Common patterns are as follows:

  • os.O_RDONLY: Read-only mode
  • os.O_WRONLY: Write-only mode
  • os.O_RDWR: Read and write mode
  • os.O_APPEND: Append mode, append to the end of the file when writing
  • os.O_CREATE: If the file does not exist, create the file
  • os.O_TRUNC: If the file already exists, clear the file contents

5.2 Example: Use append writes

The following example shows how to open a file and write content in append mode:

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := ("", os.O_APPEND|os.O_WRONLY, 0644)
    if err != nil {
        ("Failed to open the file:", err)
        return
    }
    defer ()

    _, err = ("Add content\n")
    if err != nil {
        ("Write failed:", err)
    } else {
        ("Add content is successful")
    }
}

5.3 The meaning of file permission 0644

existmiddle,0644Indicates the filePermissions

  • This value is an octal number consisting of three sets of permissions:rwx(Read, write, execute).
  • Each group corresponds to a user type:
    • The first group: File owner permissions
    • The second group: User permissions for the group where the file resides
    • Group 3: Other user permissions

0644Specific meaning:

  • 6: The file owner has read (4) and write (2) permissions
  • 4: The user in the group where the file is located has read (4) permission
  • 4: Other users have read (4) permission
User Type Permission value Permission Meaning
File owner 6 Read + Write
Group user 4 read
Other users 4 read

6. Control of file pointer

SeekMethods allow us to move the pointer in the file so that we can start reading and writing from different locations.

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := ("")
    if err != nil {
        ("Failed to open the file:", err)
        return
    }
    defer ()

    // Move the pointer to the 5th byte of the file    (5, 0)
    buffer := make([]byte, 10)
    _, err = (buffer)
    if err != nil {
        ("Read failed:", err)
        return
    }
    ("Read content:", string(buffer))
}

7. Error handling and performance optimization

  • Resource leaks due to file not being closed: Make sure to usedefer ()Release file resources in a timely manner.
  • Avoid frequent I/O operations:usebufioThe packet is buffered for reading and writing.
  • Read large files in chunks: For large files, avoid one-time reading and use streaming instead.

8. Summary

This article introduces in detail the read and write operations of files in Go language, including how to open, create files, and how to use them.bufioImprove reading and writing efficiency and the specific meaning of file permissions. With these examples, readers can easily master file operations in Go.

This is the article about reading and writing of Golang file operations. For more related Golang file reading and writing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!