SoFunction
Updated on 2025-03-05

One article will help you master the writing operations of files in Go language

Preface

Previous articleMaster the reading operations of Go files in one articleIntroduced how to use itGo osPackage andbufioSeveral functions and methods in the package show how to read the content in the file through cases. This article continues the content of the previous article, introducing the writing operation of files.

、、

(b []byte) (n int, err error)

Directly operate the disk to write data into the file, and the writing unit is bytes.

  • bParameters: Write data, type of byte slice.
  • Return valuen: The number of bytes written.
  • Return valueerr: Errors generated during writing data.

(s string) (n int, err error)

Directly operate the disk to write data into the specified file, and the writing unit is a string.

  • sParameters: written string data.
  • Return valuen: The number of bytes written.
  • Return valueerr: Errors generated during writing data.

(b []byte, off int64) (n int, err error)

From the specified locationoffWrite data into the file in sequence, and if there is data on an offset, it will be overwritten.

  • bParameters: Write data, type of byte slice.
  • offParameters: Offset, starting from this position to write data.
  • Return valuen: The number of bytes written.
  • Return valueerr: Errors generated during writing data.

File writing operation

import (
    "fmt"
    "os"
)

func main() {
    file, err := ("", os.O_CREATE, 0)
    if err != nil {
            (err)
            return
    }
    defer ()
    count, err := ([]byte{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\n'})
    if err != nil {
            return
    }
    ("Written %d byte\n", count)
    count, err = ("Hello Golang")
    if err != nil {
            return
    }
    ("Written string of length %d\n", count)
    count, err = ([]byte{'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x', 'x'}, 0)
    if err != nil {
            return
    }
    ("Written %d byte\n", count)
}

Open firstfile, specified mode isos.O_CREATE, if the file does not exist, it will be created automatically;

Then passWriteMethods are written into the file in the form of charactersHello World\ncontent;

Then passWriteStringMethods are written into the file as stringsHello GolangContent; the content in the file is as follows:

Hello World
Hello Golang

Last passedWriteAtMethod, specifying the offset from0start writing data at the locationxxxxxxxxxxx,because0There is data at the location afterwards, so the original data is overwritten. The contents of the last file are:

xxxxxxxxxxx
Hello Golang

(offset int64, whence int)

Set the offset to set the current read or write relative to the beginning or current position or end position.offset

  • offsetParameters: The offset to be set.
  • whence: The offset flag relative to which position starts to be set, the optional value is0→ the beginning position,1→ Current location,2→ The end position.

application

import (
    "fmt"
    "os"
)

func main() {
    file, err := ("", os.O_CREATE, 0)
    if err != nil {
            (err)
            return
    }
    defer ()
    _, err = ("G0lang")
    if err != nil {
            return
    }
    _, err = (1, 0)
    if err != nil {
            (err)
            return
    }
    _, err = ([]byte{'o'})
    if err != nil {
            (err)
            return
    }
}
  • Openfile, specified mode isos.O_CREATE, if the file does not exist, it will be created automatically;
  • useWriteStringMethods to write to the fileG0langstring;
  • At this time, I found that the second character was wrong.0It should be changed too;The offset at this time points to the tail; useSeekMethod moves the offset to the second position and then writes the charactero, because there is data at the current location0,thereforeoWill cover0

、、

If you need to write to a file multiple times, it is recommended to usebufioInsideWriterTo operate the structure, it will open a buffer, the default size is4096byte. Before the data is flushed to disk, the written data will be temporarily saved to the buffer.

NewWriter(w ) *Writer

Open a default value as4096Buffer of bytes, used to temporarily store the data content written to the file, and return aWriterPointer variables for structures

  • wParameter: Type isWriterThe data type variables that implement this interface can be used as parameters, for exampleFile
  • Return value*Writer:oneWriterA pointer variable to the structure, through which data can be written into the buffer.

(s string) (int, error)

How to write content into the buffer.

  • parametersis a written string.
  • The first return value is the number of bytes written.
  • The second return value is an error generated during the writing process of data.

() error

Write all cached data to disk.

The return value is an error generated during the process of writing data to disk.

File writing operation

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

func main() {
    file, err := ("", os.O_CREATE, 0)
    if err != nil {
            (err)
            return
    }
    defer ()
    writer := (file)
    _, err = ("Hello World\n")
    if err != nil {
            (err)
            return
    }
    _, err = ("Hello Golang\n")
    if err != nil {
            (err)
            return
    }
    _, err = ("Hello Gopher\n")
    if err != nil {
            (err)
            return
    }
    ()
}
  • Open firstfile, specified mode isos.O_CREATE, if the file does not exist, it will be created automatically;
  • Then useNewWriterFunction gets aWriterPointer variables for structureswriter
  • Then passwriterofWriteStringMethod saves the content to the buffer;
  • Last callFlushMethod, write all cached data to disk.

summary

This article is correct firstMake an introduction, demonstrate how they are used through examples; then introduce, explains its usage; finally leads to, use them instead of the writing method in the File structure, so that the disk can be operated frequently and the writing efficiency can be improved.

This is the article about this article that will lead you to master the writing operation of files in Go. For more relevant Go file writing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!