SoFunction
Updated on 2025-03-04

The underlying principle of Go language IO input and output and file operation API

1. The underlying principle of input and output

The terminal is actually a file, and the relevant examples are as follows:

  • : Standard input file instance, type *File
  • : The file instance of standard output, type *File
  • : The file instance output by standard error, type *File

Operate the terminal as a file:

package main
import "os"
func main() {
    var buf [16]byte
    (buf[:])
    (string(buf[:]))
}

2. File operation related API

  • func Create(name string) (file *File, err Error) Create a new file based on the provided file name and return a file object. The default permission is 0666
  • func NewFile(fd uintptr, name string) *File Creates the corresponding file according to the file descriptor and returns a file object
  • func Open(name string) (file *File, err Error) Open a file named name read-only
  • func OpenFile(name string, flag int, perm uint32) (file *File, err Error) Open a file with name, flag is the way to open it, read only, read and write, etc., perm is the permission
  • func (file *File) Write(b []byte) (n int, err Error) Write information of type byte to the file
  • func (file *File) WriteAt(b []byte, off int64) (n int, err Error) Start writing information of byte type at the specified location
  • func (file *File) WriteString(s string) (ret int, err Error) Write string information to the file
  • func (file *File) Read(b []byte) (n int, err Error) Read data into b
  • func (file *File) ReadAt(b []byte, off int64) (n int, err Error) Read data from off to b
  • func Remove(name string) Error Delete the file with the file name

3. Open and close files

The () function can open a file and return a *File and an err. Calling the close() method on the obtained file instance can close the file.

package main
import (
    "fmt"
    "os"
)
func main() {
    // Open the files in the current directory by read-only    file, err := ("./")
    if err != nil {
        ("open file failed!, err:", err)
        return
    }
    // Close the file    ()
}

4. Write a file

package main
import (
    "fmt"
    "os"
)
func main() {
    // Create a new file    file, err := ("./")
    if err != nil {
        (err)
        return
    }
    defer ()
    for i := 0; i < 5; i++ {
        ("ab\n")
        ([]byte("cd\n"))
    }
}

5. Read the file

File reading can be done using () and (). The error will be returned when reading the end of the file.

package main
import (
    "fmt"
    "io"
    "os"
)
func main() {
    // Open the file    file, err := ("./")
    if err != nil {
        ("open file err :", err)
        return
    }
    defer ()
    // Define the byte array of received file read    var buf [128]byte
    var content []byte
    for {
        n, err := (buf[:])
        if err ==  {
            // Reading ends            break
        }
        if err != nil {
            ("read file err ", err)
            return
        }
        content = append(content, buf[:n]...)
    }
    (string(content))
}

6. Copy the file

package main
import (
    "fmt"
    "io"
    "os"
)
func main() {
    // Open source file    srcFile, err := ("./")
    if err != nil {
        (err)
        return
    }
    // Create a new file    dstFile, err2 := ("./")
    if err2 != nil {
        (err2)
        return
    }
    // Buffered read    buf := make([]byte, 1024)
    for {
        // Read data from source files        n, err := (buf)
        if err ==  {
            ("Reading Completed")
            break
        }
        if err != nil {
            (err)
            break
        }
        //Write it out        (buf[:n])
    }
    ()
    ()
}

7. bufio

  • The bufio package implements read and write with buffer, which is an encapsulation of file read and write.
  • Bufio buffer write data

os.O_WRONLY //Write only os.O_CREATE //Create file os.O_RDONLY //Read only

os.O_RDWR //Read and write os.O_TRUNC //Clear os.O_APPEND //Add

  • bufio read data
package main
import (
    "bufio"
    "fmt"
    "io"
    "os"
)
func wr() {
    // Parameter 2: Turn on mode, all modes d are on    // Parameter 3 is permission control    // w write r read x execute w 2 r 4 x 1    file, err := ("./", os.O_CREATE|os.O_WRONLY, 0666)
    if err != nil {
        return
    }
    defer ()
    // Get the writer object    writer := (file)
    for i := 0; i < 10; i++ {
        ("hello\n")
    }
    // Fresh the buffer and force it to write it out    ()
}
func re() {
    file, err := ("./")
    if err != nil {
        return
    }
    defer ()
    reader := (file)
    for {
        line, _, err := ()
        if err ==  {
            break
        }
        if err != nil {
            return
        }
        (string(line))
    }
}
func main() {
    re()
}

The above is the detailed content of the underlying principles of Go IO input and output and file operation API. For more information about Go IO operation input and output API, please pay attention to my other related articles!