SoFunction
Updated on 2025-03-05

A comprehensive explanation of Go file reading and writing operations

Reading operations of Go files

os package and bufio package

Go standard libraryosPackage provides us with many functions that operate files, such asOpen(name)Open the file,Create(name)Create files and other functions, corresponding to them isbufioBag,osThe package operates directly on the disk, andbufioThe package is a buffered operation, and you don’t have to operate the disk every time.

and

  • Open(name string) (*File, error)

    passfile nameorFile path + file nameOpen a file in the form of  , this file can only be used for reading operations, and if the file does not exist, it will be returnedPathError 。

    • Parametersnameforfile nameorFile path + file name
    • Return value*FileFor oneFileThe pointer type of the structure, through which pointers can read and write files, etc.

Return value

`error` is an error that occurs during the process of opening the file.

OpenFile(name string, flag int, perm FileMode) (*File, error)

By specifyingfile nameorFile path + file nameOpen a file with three parameters: file operation mode, and file permissions, and then read and write operations on the file.

  • Parametersnameforfile nameorFile path + file name
  • ParametersflagTo specify the file operation mode, optional values ​​areO_RDONLY→ Read-only operation,O_WRONLY→ Write-only operation,O_RDWR→ Read and write operations,O_APPEND→ Append data to the file during writing,O_CREATE→ If it does not exist, create a new file, etc.
  • ParameterspermParameters represent the file's pattern and permissions, for example0666For read and write permissions. If you don't understand the number corresponding to file permissions, you can learn it.
  • Return value*FileFor oneFileThe pointer type of the structure, through which pointers can read and write files, etc.
  • Return valueerrorAn error occurred during the process of opening the file.

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

Read andbbytes of equal length and stored inbin.

  • Parametersbis a slice array that specifies the read length and store byte data.
  • Return valuenThe length of the bytes read.
  • Return valueerrorAn error occurred during the reading of bytes.

Read file operation

import (
    "fmt"
    "os"
)
func main() {
    file, err := ("")
    if err != nil {
        (err)
        return
    }
    defer ()
    data := make([]byte, 11)
    count, err := (data)
    if err != nil {
        return
    }
    ("Byte Data:", data)          // [72 101 108 108 111 32 119 111 114 108 100]
    ("String data:", string(data)) // Hello world
    ("Length of the retrieved bytes:", count)     // 11
}

Execution results:

Byte data: [72 101 108 108 111 32 119 111 114 108 100]
String data: Hello world
The length of the obtained bytes: 11

  • First passOpenFunction openFile, usefileVariable reception, default to readable mode;
  • Then create a length of11byte slice, then passfileVariable methodReadThe read length is11byte data.("")Equivalent to("", os.O_RDONLY, 0)
  • Finally, print the read data. After the file operation is completed, the file needs to be closed.()

and

Read files, it is recommended to useand, reduce disk operation.

  • NewReader(rd ) *ReaderGet a buffered oneReaderPointer variable, the default buffer size is4096byte. The data can be read through variables.

    • ParametersrdAs an interface, all data type variables that implement this interface can be used as parameters, such as the above mentionedFile
    • Return value*ReaderforReaderPointer to the structure, the buffer data can be read through the pointer.
  • ReadString(delim byte) (string, error)Read data until the first time you encounter a separatordelimSo far. An error occurs during reading process will returnEOFerror message.

    • ParametersdelimIt is a delimiter, and it will terminate every time it is read.
    • The first return value is the read content, including the separator.
    • The second return value is the error message generated during the reading process.

Read file operation

The content of the file is:

Hello world
Hello Golang
Hello Gopher

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

func main() {
    file, err := ("", os.O_RDONLY, 0)
    if err != nil {
        (err)
        return
    }
    defer ()
    reader := (file)
    for {
        if lineData, err := ('\n'); err != nil {
            if err ==  {
                // Because the line break is used as the separator, if there is no line break on the last line, then when the error is returned, the data may be read. Therefore, determine whether the data has been read.                if len(lineData) > 0 {
                    (lineData)
                }
                break
            }
        } else {
            ((lineData, "\n"))
        }
    }
}

Execution results:

Hello World
Hello Golang
Hello Gopher

  • First passOpenFileFunction openFile, usefileVariable reception, specified as readable mode;
  • Then passNewReaderThe function creates a buffer and reads bytes of default length into the buffer;
  • Then passReaderStructural methodReadString,by\nAs a separator, read the data by line and then print the data.
  • One of the points of attention is that because the newline is used as the separator. If there is no newline on the last line, then returnWhen there is an error, data may also be read, so you need to determine whether the data has been read.

Go file write operation

、、

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

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

    • bParameters: The written 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 a certain offset, it will be overwritten.

    • bParameters: The written 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

Finally passedWriteAtMethod, specify the slave offset as0Start 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 the current position or the end position.offset

    • offsetParameters: The offset to be set.
    • whence: The flag of the offset starts to be set relative to which position, 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;
  • useWriteStringMethod 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 execute the write operation to a file multiple times, it is recommended to usebufioThe insideWriterTo 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 is used to temporarily store the data content written to the file, and returns aWriterPointer variable of structure

    • wParameter: Type isWriterInterface, the data type variables that implement this interface can be used as parameters, for exampleFile
    • Return value*Writer:oneWriterPointer variable of the structure, through which data can be written into the buffer.
  • (s string) (int, error)

    How to write content into the buffer.

    • Parameterssis the 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 oneWriterPointer variables of structurewriter
  • Then passwriterofWriteStringMethod saves the content to the buffer;
  • Last callFlushMethod, write all cached data to disk.

summary

Recommended file reading operationsbufioThe one in the bagNewReaderFunctions andReaderStructural methodReadString, can reduce disk operation and read data efficiently.

Recommended file writing operations, 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.

The above is the comprehensive detailed content of Go file reading and writing operations. For more information about Go file reading and writing operations, please pay attention to my other related articles!